我有这门课:
@Transactional
@Repository("reportManagementDAO")
public class ReportManagementDAOImpl implements ReportManagementDAO,
Serializable{
@Autowired
private SessionFactory getSessionFactory;
public SessionFactory getSessionFactory(){
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
class ReportWork extends AbstractReportWork{
}
}//
abstract class AbstractReportWork extends RCDStoreProcedureWork {
void doReport() {
//How can I access to: ReportManagementDAOImpl.getSessionFactory()
//using reflection, for example:
//Class<?> type = getClass().getEnclosingClass();
}
}
如何使用反射通过外部类访问:ReportManagementDAOImpl.getSessionFactory()???
最佳答案
如果AbstractReportWork
也嵌套在 ReportManagementDAOImpl
内不是 static
,你可以通过 ReportManagementDAOImpl.this
获取当前的外部实例.
如果AbstractReportWork
未嵌套在 ReportManagementDAOImpl
内,你想要做的(虽然可能)是一个糟糕的主意,因为你引入了一个隐藏的(而且极其不寻常的)要求,即 AbstractReportWork
的继承者必须是嵌套类。这无异于地雷,所以不要这样做。
这里有更好的选择:
- 如果可能(即如果都是无状态的),
@Autowire SessionFactory
进入您需要它的类(而不是从外部类获取它,或者从任何地方手动获取它) - 否则,传递
ReportManagementDAO
的实例或SessionFactory
至ReportWork
如果需要(可能通过使doReport()
接受它:doReport(SessionFactory sessFactory){...}
或通过使构造函数接受它:ReportWork(SessionFactory sessFactory) {...}
)
如果您真的想观看世界燃烧,请反射(reflection)地获取封闭的实例:
Field this$0 = this.getClass().getDeclaredField("this$0");
//not sure if this$0.setAccessible(true); is required
ReportManagementDAO enclosing = (ReportManagementDAO) this$0.get(this);
enclosing.getSessionFactory();
但请注意,这是一个可能会在未来的 Java 版本中被破坏的 hack,因为 this$0
字段绝不是记录的 API 的一部分。
关于Java - 获取封闭实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42767714/