【问题标题】:Java - get the enclosing instance [duplicate]Java - 获取封闭实例[重复]
【发布时间】:2017-08-03 17:02:29
【问题描述】:

我有这门课:

@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()????

【问题讨论】:

  • @david-basarab 你们能在标记为重复之前阅读这个该死的问题吗?这与访问不可见的类无关。这里的external这个词的意思是outer类。没有其他相似之处。

标签: java hibernate reflection inner-classes


【解决方案1】:

如果AbstractReportWork 也嵌套在ReportManagementDAOImpl 中而不是static,则可以通过ReportManagementDAOImpl.this 获取当前外部实例。

如果AbstractReportWork 没有嵌套在ReportManagementDAOImpl 中,那么您尝试做的(可能)是一个糟糕的主意,因为您引入了AbstractReportWork 的继承者必须的隐藏(并且非常不寻常)要求是嵌套类。这简直就是地雷,所以不要这样做。

这里有更好的选择:

  1. 如果可能(即如果它都是无状态的),@Autowire SessionFactory 进入你需要它的类(而不是从外部类中获取它,或者从任何地方手动获取它)
  2. 否则,如果需要,将ReportManagementDAOSessionFactory 的实例传递给ReportWork(可能通过使doReport() 接受它:doReport(SessionFactory sessFactory){...} 或通过使构造函数接受它:ReportWork(SessionFactory sessFactory) {...}

如果你真的想看世界燃烧,反射性地获取封闭实例:

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 的一部分。

【讨论】:

    猜你喜欢
    • 2015-05-21
    • 2016-08-28
    • 2013-09-12
    • 2015-05-05
    • 2023-04-04
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    相关资源
    最近更新 更多