0

I want to find the class name of the argument sent to the generic class as follows.

public abstract class RootClass<T extends Iface> {
    protected ApplicationContext applicationContext;
    public T getIfaceBean() {
        return applicationContext.getBean(T.class);
    }
}

But it looks like I can't do T.class (due to Type Erasure?).

So, Is such an action possible with Java Generics ?

How can I achieve this type of functionality with Java Generics?

TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125
  • It's hacky, you're better off passing the Class type as an argument to the constructor or method. – Sotirios Delimanolis Jul 30 '13 at 17:10
  • Same thing as with http://stackoverflow.com/questions/75175/create-instance-of-generic-type-in-java You have to pass the class as an argument. – Cyrille Ka Jul 30 '13 at 17:11
  • 1
    You can obtain this via reflection if you have a subclass (as you must have) and concrete type. Here is an example http://ideone.com/9ZFujO – Peter Lawrey Jul 30 '13 at 17:22
  • @PeterLawrey Using reflection for this purpose seems complex. I have had figure out a simple solution by requiring concrete-classes to implement `getIfaceClass()` which just do `return SubIface.class`. – TheKojuEffect Jul 30 '13 at 17:27
  • That is fine if you don't have to do it very often. Doing what you believe is simplest is the best approach. – Peter Lawrey Jul 30 '13 at 17:34
  • @PeterLawrey Can you please help me write code in abstract class using reflection instead of implementing `getIfaceClass()` in concrete class? – TheKojuEffect Jul 30 '13 at 18:10
  • You can copy the code from my example, see the link. – Peter Lawrey Jul 30 '13 at 18:13

1 Answers1

7

Because of Type Erasure, you can't say T.class because T doesn't exist at runtime.

The best you can do is to take a parameter of type Class<T> to get the Class object:

public T getIfaceBean(Class<T> clazz) {
rgettman
  • 176,041
  • 30
  • 275
  • 357