Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

Dynamic Generic Typing in Java

If I have a class using generic type such as

public class Record<T> {
    private T value;

    public Record(T value) {
        this.value = value;
    }
}

it is pretty straight forward to type everything during design time, if I know all types that are used such as it is the case in this example:

// I type explicitly
String myStr = "A";
Integer myInt = 1;
ArrayList myList = new ArrayList();

Record rec1 = new Record<String>(myStr);
Record rec2 = new Record<Integer>(myInt);
Record rec3 = new Record<ArrayList>(myList);

What happens if I get a list of objects from "somewhere" where I don't know the type? How do I assign the type:

// now let's assume that my values come from a list where I only know during runtime what type they have

ArrayList<Object> myObjectList = new ArrayList<Object>();
    myObjectList.add(myStr);
    myObjectList.add(myInt);
    myObjectList.add(myList);

    Object object = myObjectList.get(0);

    // this fails - how do I do that?
    new Record<object.getClass()>(object);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Java generics are not C++ Templates.

Java generics are a compile time feature, not a run time feature.

Here is a link to the Java generics Tutorial.

This can never work with Java:

new Record<object.getClass()>(object);

You must either use polymorphism (say, each object implements a known interface) or RTTI (instanceof or Class.isAssignableFrom()).

You might do this:

     class Record
     {
       public Record(String blah) { ... }
       public Record(Integer blah) { ... }
       ... other constructors.
     }

or you might use the Builder pattern.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...