通用与类>
你好,我正在使用反射做一些测试...... 到目前为止,我已经得到了这个:
public class MyConveter implements Converter {
private Class<?> myClass;
public MyConveter(Class<?> myClass) {
this.myClass = myClass;
}
@Override
public boolean canConvert(Class clazz) {
return clazz.equals(myClass);
}
@Override
public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
// TODO Auto-generated method stub
}
@Override
public Object unmarshal(HierarchicalStreamReader arg0, UnmarshallingContext arg1) {
try {
Object obj = myClass.newInstance();
Field daoField = myClass.getDeclaredField("id");
daoField.setAccessible(true);
daoField.set(obj, Integer.valueOf(5));
Field daoField2 = myClass.getDeclaredField("value");
daoField2.setAccessible(true);
daoField2.set(obj, "proj name");
return obj;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
但我不喜欢结果,有没有办法将其更改为:
public class MyConveter<T> implements Converter;
从而删除构造函数?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以用你想要的类型参数来声明你的类;但是,您确实需要尝试转换的类的实例(因为它在
unmarshal
方法中使用)。编译类后,泛型中的所有类型信息都会被删除,因此运行时无法知道要为哪个类创建新实例。You can declare your class with a type parameter all you want; you do, however, need an instance of the class you are trying to convert (because it is used in the
unmarshal
method). All type information from generics is removed after compiling the class so the runtime has no way of knowing what class to create a new instance for.不,除非您更改呼叫,否则您不能这样做
。您的更改
将与 api 更改同时进行。
另外,基本上,在使用像此类这样的泛型时,您只是说您没有定义允许的任何特定对象,该对象可以是任何东西(任何对象或其子类),请
阅读Effective java或Angelika Laker FAQ以获取更多详细信息。
No you can't do that unless and until you change
Call. Your change to
will go hand in hand with the api change.
And plus basically while using generice like this Class you are just saying that you dont have any specific object defined to be allowed which can be anything (any Object or its subclass)
Read Effective java or Angelika Laker FAQ for more detail on this.