【发布时间】:2019-11-22 03:16:39
【问题描述】:
我期望完成的事情(如果可能的话):
我正在玩 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 并让工厂做其他所有事情,这只是我想到的一个实验。
是否可以进行这种铸造?
【问题讨论】:
-
这能回答你的问题吗? Create new object using reflection?
-
@AlexeiLevenkov 谢谢,对不起,我花了一段时间才明白,但是如果我特别需要使用强制转换怎么办?有可能吗?
-
您的问题是“为什么投射不能将结果
new SomeType1()转换为SomeUnrelatedType?”非常不清楚你想在哪里使用强制转换... -
@AlexeiLevenkov 我应该从一开始就更好地解释自己,你介意再看看我的帖子吗?
-
Jouo 与以前的编写方式相比,这是一个非常不同(而且看起来更好看)的问题。 Enrico 的答案(本质上是
Class<T> clazz;)似乎是答案......除非你正在寻找其他东西......