从包名称加载类并从模板类创建对象

时间:2019-01-10 10:20:23

标签: java templates generics classloader

我有一个像这样的模板类-

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;
    }

    // other methods and members
}

,我有一个名为Skill的节点类,

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;
    }

    // other methods.
}

我可以使用这样的NodeDAO类来创建Skill对象-

NodeDAO<Skill> skillNodeDAO = new NodeDAO<Skill>(session, Skill.class);

每件事看起来都不错,但是现在我有一个要求,在此位置我已获得文件的路径,并且必须为其动态创建NodeDAO对象。我试图遵循本教程-Dynamic Class Loading在运行时加载类。我想出了这段代码。

public void createDAO object(){
    ClassLoader classLoader = this.getClass().getClassLoader();
    Class<?> loadedClass = classLoader.loadClass(fullPath);
    NodeDAO<loadedClass> DAOClass = getGraphNodeDAO(graphIdentifier, loadedClass);
    // Above line or below line throws the same error - cannot be resolved into a type
    //NodeDAO<loadedClass> DAOClass = getGraphNodeDAO(graphIdentifier, loadedClass.getClass());

    // use loadedClass to do other stuffs....
}

我收到以下错误-

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    loadedClass cannot be resolved to a type

0 个答案:

没有答案