0

here's my code:

AbstractClass

public abstract class AbstractClass<T>{

    public abstract Class<?> getPersistentClass();

    public void invokeNothing(){
        Class<T> c = getPersistentClass();
        // do something....
        // some code...
    }

}

CommonClass

public class CommonClass<T> extends AbstractClass<T>{

    public Class<?> getPersistentClass(){
        // how to get the persistent class of generic T
        // T.class
        return // T.class
    }

}

Service

public class CommonService{

    @Autowired
    private CommonAbstractClass<Person> commonClass;

    public void invoke(){
        commonClass.invokeNothing();
    }


}

how to get the persistent class parameter of a class generic? in my class CommonClass in method getPersistentClass();

please help me thanks...

teodoro
  • 247
  • 7
  • 21

1 Answers1

0

Actually there is no way (at least no easy way I am aware of except reflection in some cases) to get the runtime type of the generic type parameter due to type erasure. You can use the following safe work-around:

public class CommonClass<T>{

    private final Class<T> type;

    public CommonClass(Class<T> type) {
        this.type = type;
    }

    public Class<T> getMyType() {
        return this.type;
    }

}

But you may need to instantiate it like:

CommonClass<Person> cp = new CommonClass<Person>(Person.class);

If you are using Spring you can find this answer useful.

Community
  • 1
  • 1
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
  • but i am using a spring @Autowired. just want to have it without a instantiating the constuctor with arguments. is there any way to do that? – teodoro Oct 19 '15 at 05:28