简体   繁体   English

Java反射:在初始化期间设置超类字段

[英]Java reflection : set super class field during initialization

I make initialization a of a new class by reflection and I set one superclass field with 'this': 我通过反射将新类初始化为a,并用'this'设置了一个超类字段:

JavaTask jt = (JavaTask) clazz.newInstance();
for(Field f : clazz.getSuperclass().asSubclass(JavaTask.class).getDeclaredFields()) {
    if(f.getType().equals(JavaTaskListener.class)) {
        logger.trace("Set ReadyListener");
        f.setAccessible(true);
        f.set(jt, this);
    }
}

In such a solution I can access 'this' from a new instance jt after completion of initialization. 在这种解决方案中,初始化完成后,我可以从新实例jt访问“ this”。 Would it be possible to somehow set jt after creation of superclass and before creation of base class that I could access 'this' during initialization (without adding non default construction)? 在创建超类之后以及在创建基类之前可以在初始化期间访问“ this”(不添加非默认构造)的基础上设置jt吗?

public class LocalMotions extends JavaTask {
   ...
  private int nb = super.jtListener.getParameter(NUMBER));
   ...

Publishing a reference to an object before it is fully constructed is dangerous for the JVM, and strongly discouraged. 在完全构造对象之前发布对对象的引用对于JVM是危险的,因此强烈建议不要这样做。

When JSR-133 was in the works, and the java memory model was clarified it was stated that the JVM makes no thread safety guarantees for references to an object that is leaked out during construction. 当JSR-133投入使用并阐明了Java内存模型时,有人说JVM不会为对在构造期间泄漏的对象的引用提供线程安全保证。 That is, it becomes possible for references to leak between threads that have been allocated but not zeroed out etc. 也就是说,引用可能会在已分配但未清零的线程之间泄漏。

For more details, research JSR 133, the Java Memory Model and 'safe construction techniques'. 有关更多详细信息,请研究JSR 133,Java内存模型和“安全构造技术”。 http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight is a good starting point. http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight是一个很好的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM