我期望完成的目标(如果可能的话):
我在玩Hibernate,我只想制作一个类来处理不同对象/实体的简单CRUD。我完全知道这可能是不好的做法,但这只是出于学习目的的实验。
我正在尝试做的简短示例
public class TestFactory {
private Class classType;
private String configuration;
public TestFactory(Class classType, String XML) {
this.classType = classType;
this.configuration = configurationName(XML);
}
private SessionFactory getSessionFactory() {
return new Configuration()
.configure(this.configuration)
.addAnnotatedClass(this.classType)
.buildSessionFactory();
}
public <T> T get(int id) {
try (SessionFactory factory = getSessionFactory();
Session session = factory.getCurrentSession()) {
session.beginTransaction();
// Attempting to cast the result to the class required
T object = this.classType.cast(session.get(this.classType, id));
session.getTransaction().commit();
return object;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
预期用途
TestFactory factory = new TestFactory(JustSample.class, "A-conf.xml")
// Should return the object casted to a JustSample class
JustSample sample = factory.get(5);
TestFactory factory = new TestFactory(AnotherSample.class, "B-conf.xml")
// Should return the object casted to a AnotherSample class
AnotherSample another = factory.get(5);
所以我的想法是传递任何Class.class并让工厂进行其他所有操作,这只是我想到的一个实验。
可以进行这种铸造吗?
最佳答案
尝试此操作,不确定是否正是您要的内容。
public class SimpleClass<T> {
private final Class<T> clazz;
SimpleClass(Class<T> clazz) {
this.clazz = clazz;
}
public T getObject() throws IllegalAccessException, InstantiationException {
// Should return a new object based on the class type
return clazz.newInstance();
}
}