访问通用类成员并获取Java中的类类型

时间:2019-01-03 06:49:27

标签: java generics reflection

我正在尝试为neo4j中的图形节点创建一个通用DAO类。我有多个图节点类。其中之一看起来像这样

import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.Relationship;

public class Skill {
    @Id @GeneratedValue
    private Long id;
    private String Name;
    private String CleanedText;
    public final static String GraphIdentifier = "skill-ontology";

    @Relationship(type = "BelongsTo", direction = Relationship.OUTGOING)
    private Set<SkillSubCluster> belongsTo = new HashSet<>();

    public Long getId() {
        return id;
    }

    public String getName() {
        return Name;
    }

    public String getCleanedText() {
        return CleanedText;
    }
}

我的GenericDAO类是-

public class NodeDAO<T> {
    private static final int DEPTH_LIST = 0;
    private static final int DEPTH_ENTITY = 1;
    final Class<T> typeParameterClass;
    private Session session;

    public NodeDAO(Session session, Class<T> typeParameterClass) {
        this.session = session;
        this.typeParameterClass = typeParameterClass;
    }

    public NodeDAO(Session session) {
        this.session = session;
        this.typeParameterClass = getEntityClass();
    }

    public Class<T> getEntityClass() {
        ParameterizedType parameterizedType = (ParameterizedType) getClass()
                .getGenericSuperclass();

        @SuppressWarnings("unchecked")
        Class<T> ret = (Class<T>) parameterizedType.getActualTypeArguments()[0];

        return ret;
    }


    protected Class<T> getEntityType() {
        return (Class<T>) this.typeParameterClass;

    }

    public Iterable<T> findAll() {
        return session.loadAll(getEntityType(), DEPTH_LIST);
    }

    // rest of the implementation
}

然后有我的经理类负责与多个图实例建立连接,这些实例的一种方法是-

public <T> NodeDAO<T> getGraphNodeDAO(String graphDBIdentifier, Class<T> typeParameterClass){   

        // graphSessions is a hashmap<String, Session> storing multiple neo4j instances sessions. A session is identified by a graphDBIdentifier string
        Session session = graphSessions.get(graphDBIdentifier);
        // This works
        NodeDAO<T> nodeDAO = new NodeDAO<T>(session, typeParameterClass);
        //NodeDAO<T> nodeDAO = new NodeDAO<T>(session);
        return nodeDAO;
    }

调用此方法是为了获取给定图节点的DAO对象

NodeDAO<Skill> skillNodeDAO = manager.getGraphNodeDAO(Skill.GraphIdentifier, Skill.class); 

代码工作正常,但是我希望管理器类getGraphNodeDAO方法根据类传递(基于GraphIdentifier的类变量Skill自动知道要加载哪个会话类) 和NodeDAO类,以自动识别class type,而无需显式传递它。

调用NodeDAO<T> nodeDAO = new NodeDAO<T>(session);会引发以下错误

Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

0 个答案:

没有答案