简体   繁体   English

反射getDeclaredMethods()和不在类路径中的类

[英]Reflection getDeclaredMethods() and class that is not in classpath

I am using reflection to get all methods from a specific class. 我正在使用反射来获取特定类的所有方法。

This class has references to class that not in my class path so I get an exception: 此类引用的类不在我的类路径中,因此出现异常:

java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError:

On this: 在此:

Method methods[] = theClass.getDeclaredMethods();

Is it possible, somehow,to "skip" everything that is not in classpath? 是否有可能以某种方式“跳过”类路径以外的所有内容?

Class.forName() will not load a class, whether it is or isn't in the classpath. 无论是否在类路径中,Class.forName()都不会加载该类。 It will only return a handle to a class that is already loaded. 它将仅返回已加载的类的句柄。

A class gets loaded in one of 2 main ways: 类可以通过以下两种主要方式之一进行加载:

1.)The class is referenced in the import statements(java.lang.* is imported automatically so every class in java.lang package is class-loaded from the start) 1.)该类在import语句中被引用(java.lang。*是自动导入的,因此java.lang包中的每个类都是从一开始就加载类的)

2.)A class is loaded using a call from a ClassLoader, in which case all of its dependencies are resolved. 2)使用来自ClassLoader的调用来加载类,在这种情况下,其所有依赖项都将被解析。 and loaded as well 并加载

So if you are trying to load a class outside of the classpath, or with dependencies outside the classpath, you need to subclass ClassLoader and tell it how to load your classes and their dependencies. 因此,如果您尝试在类路径之外加载类,或者在类路径之外加载依赖项,则需要对ClassLoader进行子类化,并告诉它如何加载类及其依赖项。

See ClassLoader specification here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/ClassLoader.html 请参阅此处的ClassLoader规范: http : //docs.oracle.com/javase/1.4.2/docs/api/java/lang/ClassLoader.html

Also, there are ready made subclasses of ClassLoader that may do what you want such as URL ClassLoader which will let you simply point the ClassLoader instance at the path, and load any classes in that path. 另外,还有现成的ClassLoader子类可以完成您想要的事情,例如URL ClassLoader,它使您可以简单地将ClassLoader实例指向路径,并在该路径中加载任何类。

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

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