简体   繁体   中英

How to get generic class in java

For example, I have classes:

SuperClass.java:

public class SuperClass<A extends ClientsDTO> {

    ...
    private A getChildsGenericClass{
        //???
    }
}

User.java

class User extends SuperClass<UserDTO> {
    ...
}

So how can I access UserDTO's class in SuperClass 's in getChildsGenericClass method?

you did not pass an instance of UserDTO to the superclass.
without instance, which objects fields do you want to access?

When you want to access UserDTO class, you can easily write:

Class c = UserDTO.class;

in other case, maybe you want something like this:

public class SuperClass<T extends ClientsDTO> {

    private Class<T> m_clz;
    public NewClass(Class<T> p_clz)
    {
       m_clz = p_clz;
    }

    private Class<T> getChildsGenericClass()
    {
       return m_clz;
    }

}

public A example; //this is variable from you can get Class
private Class<Object> getChildsGenericClass() {
        return (Class)((ParameterizedType)
                 (this.getClass().getGenericSuperclass()))
                                      .getActualTypeArguments()[0];
    }

that actually works!

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