Creating a generic object using a Class<?> variable
I have a generic class A, and I'm in a method where I have to create an instance of A based on the class the given object is. That is, I have:
public void (Object obj) {
Class<?> c = obj.getClass();
A<c> = ...;
}
However, on the third line Eclipse says that c cannot be resolved to a type.开发者_运维百科 When I remove the generic parameter, I get "A is a raw type. References to generic type A should be parameterized."
What would be the correct way to go here?
Thanks.
public <C> void (Object B) {
Class<C> c = B.getClass();
A<C> a = ...;
}
or even better
public <C> void (C B) {
Class<C> c = B.getClass();
A<C> a = ...;
}
or if you just need the Class
public <C> void (Class<C> clazz) {
A<C> a = ...;
}
c
is an object. And you can only give the Class while defining the generic variable.
So A<'ClassName'>
is the correct way to do that.
精彩评论