2014-10-31 75 views
0

question I asked earlier我知道为了确保某些注释存在或不在某个类的某个位置,我需要使用可以访问注解和类的类加载器重新加载它。如何重新加载一个类,使注解变得可见?

现在我正在努力如何这样的类加载器工作。在我的设置中,我只是将注释标记为java.lang.Class实例,并且可能使用该注释注释的类也是java.lang.Class实例。两者都可能被一些我不知道的不同类加载器加载(类可能被远程加载,因此它们不在本地文件系统中)。

在寻找我found this JoinClassLoader

/** 
* A class loader that combines multiple class loaders into one.<br> 
* The classes loaded by this class loader are associated with this class loader, 
* i.e. Class.getClassLoader() points to this class loader. 
* <p> 
* Author Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland, www.source-code.biz<br> 
* License: LGPL, http://www.gnu.org/licenses/lgpl.html<br> 
* Please contact the author if you need another license. 
*/ 
public class JoinClassLoader extends ClassLoader { 

private ClassLoader[] delegateClassLoaders; 

public JoinClassLoader (ClassLoader parent, ClassLoader... delegateClassLoaders) { 
    super (parent); 
    this.delegateClassLoaders = delegateClassLoaders; } 

protected Class<?> findClass (String name) throws ClassNotFoundException { 
    // It would be easier to call the loadClass() methods of the delegateClassLoaders 
    // here, but we have to load the class from the byte code ourselves, because we 
    // need it to be associated with our class loader. 
    String path = name.replace('.', '/') + ".class"; 
    URL url = findResource(path); 
    if (url == null) { 
     throw new ClassNotFoundException (name); } 
    ByteBuffer byteCode; 
    try { 
     byteCode = loadResource(url); } 
    catch (IOException e) { 
     throw new ClassNotFoundException (name, e); } 
    return defineClass(name, byteCode, null); } 

    // some code omitted 

} // end class JoinClassLoader 

所以我的问题是这样的:

鉴于C任意类可以由任意的类加载器加载注释类A的类实例的类实例。使用CA的类加载器按照该顺序实例化JoinClassLoader作为委派类加载器。请问JoinClassLoader在调用findClass时重新加载类C,以便在实际注释C时注释A始终可见?如果不是这样的类加载器实际上是怎样的?

回答

0

在我提出的问题前,我才知道,为了真正 肯定一些注释是在I类 需要与同时访问一个类加载器加载它存在或不存在的地方 - 注释和类。

如果一个类已经被一个可能无法访问所有注解的类加载器加载,我可以相信这是真的。不过,我认为你得出了错误的结论。

如果您希望能够在运行时反思分析类的注释,那么最好的解决方案不是重新加载它。相反,您应该确保通过类加载器将第一个地址加载到中,该类加载器也可以查看感兴趣的注释。 (如果结果不够充分,那么我不明白你可以怎样期待重新加载来帮助。)

在任何情况下,重新加载类给你一个不同的类(同名),甚至如果它的字节码与先前加载的版本的字节码相同。将它用于反射分析以外的任何东西都很棘手,而且很难确定这两个类实际上是否具有相同的字节码。重新加载肯定不会用新加载的替换现有的类。所有的乐趣可以随之而来。

相关问题