开发者

Creating a generic object using a Class<?> variable

开发者 https://www.devze.com 2023-03-16 21:59 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消