user952887
user952887

Reputation: 425

Generic vs Class<?>

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?

Upvotes: 0

Views: 184

Answers (2)

manocha_ak
manocha_ak

Reputation: 902

No you can't do that unless and until you change

@Override
public boolean canConvert(Class clazz) {
}

Call. Your change to

public class MyConveter<T> implements Converter;

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.

Upvotes: 0

Bombe
Bombe

Reputation: 83845

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.

Upvotes: 2

Related Questions