简体   繁体   中英

Find the Class Reference Of Genric Type

@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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM