Home > Software design >  Find the Class Reference Of Genric Type
Find the Class Reference Of Genric Type

Time:12-28

@Service
public abstract class MainService<E extends AbstractEntity, R extends MainRepository<E>> {

    @Autowired
    MainRepository<E> repository;

    public E find(long id) throws Exception {
        return this.repository.find(---, id);
    }
}

Here is it possible to find the class reference of the generic type E to pass through this method as first argument instead of the --- ...?

My expectation about the implementation is to create a generic call to avoid the repetition of the below code in all service classes.

return this.repository.find(Entity.class,id);

CodePudding user response:

Yes, here's an example of doing that:

import java.lang.reflect.ParameterizedType;

public class Foo {
    public static abstract class Bar<E> {
        public E returnAnE() throws InstantiationException, IllegalAccessException {
            Class e = (Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            return (E)e.newInstance();
        }
    }

    public static class Baz extends Bar<String> {

    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Baz baz = new Baz();
        String s = baz.returnAnE();
    }
}

This code will fail with class structures which don't match what we have here, so you should do instance of checks instead of casts, and check array accesses.

  • Related