Hello I’m doing some tests using reflection…
so far I’ve got this:
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;
}
}
But I don’t like the outcome is there a way of changing this to:
public class MyConveter<T> implements Converter;
thus removing the constructor?
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
unmarshalmethod). 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.