Suppose I have:
ClassA extends SuperClass{ ...}
ClassB extends SuperClass{ ... }
also ClassX<T extends SuperClass> { ... }
Now, during runtime I have come across an object which I know should be one of ClassA or ClassB. And I want to create an instance of ClassX based on that. How can I do that?
I have tried:
Class<?> className = object.getClass();
Class<className> objectx = ...
which does not work.
Thanks in advance!
ClassX<SuperClass> myObj = new ClassX<SuperClass>();
With a generic Class you just say, that you can have a Value in that class which is that generic Type
ClassX<T extends SuperClass>{
public T value; // its just public so i dont need a setter
}
Now you can do: theObjectThatIsAOrB = xy.get() //now you get your Object which is ClassA or ClassB
ClassX<SuperClass> myObj = new ClassX<SuperClass>();
myOjb.value = theObjectThatIsAOrB;
This is not possible, because it would not make sense. Think about it, if you could do this, what good would it do? A type parameter's only purpose is type checking at compile-time. So if you have a type parameter that you don't know at compile time, it can't type check, and it can't do anything; so there's no point in having the type parameter in the first place. (Using a wildcard would be no different.)
If the compiler can tell which of A or B is involved, just use new.
public <T extends SuperClass> ClassX <T> makeClassXInstance( T aOrB ) {
return new ClassX<T>();
}
If, on the other hand, you're looking to determine the class at runtime, something like this might work. But you're running into the variant type problem. Java sucks at solving it.
public <T extends SuperClass> ClassX <T> makeClassXInstance( T aOrB ) {
return new ClassX<T>( aOrB.getClass() );
}
public class ClassX<T>{
public ClassX( Class<T> cls ) {...}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.