31 java reflection
我正在玩Reflection,我想我会创建一个加载类的东西并打印出类中所有字段的名称.我已经制作了一个小型的hello world类,需要检查一下:
kent@rat:~/eclipsews/SmallExample/bin$ ls
IndependentClass.class
kent@rat:~/eclipsews/SmallExample/bin$ java IndependentClass
Hello! Goodbye!
kent@rat:~/eclipsews/SmallExample/bin$ pwd
/home/kent/eclipsews/SmallExample/bin
kent@rat:~/eclipsews/SmallExample/bin$
Run Code Online (Sandbox Code Playgroud)
基于以上所述我得出两个结论:
然后使用Reflection的代码:(标记导致异常的行)
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class InspectClass {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ClassNotFoundException, MalformedURLException {
URL classUrl;
classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/IndependentClass.class");
URL[] classUrls = { classUrl };
URLClassLoader ucl = new URLClassLoader(classUrls);
Class c = ucl.loadClass("IndependentClass"); // LINE 14
for(Field f: c.getDeclaredFields()) {
System.out.println("Field name" + f.getName());
}
}
}
Run Code Online (Sandbox Code Playgroud)
但当我运行它时,我得到:
Exception in thread "main" java.lang.ClassNotFoundException: IndependentClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at InspectClass.main(InspectClass.java:14)
Run Code Online (Sandbox Code Playgroud)
我的问题:
Mic*_*ers 38
从构造函数的JavadocsURLClassLoader(URL[]):
使用默认委托父ClassLoader为指定的URL构造新的URLClassLoader.首次在父类加载器中搜索后,将按照为类和资源指定的顺序搜索URL.任何以"/"结尾的URL都被假定为引用目录.否则,假定URL引用JAR文件,该文件将根据需要下载和打开.
所以你有两个选择:
(1)在这种情况下更容易,但是(2)如果你使用网络资源可以很方便.
Mau*_*rry 10
您必须将包含.class文件的目录或jar文件提供给URLClassLoader:
classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/");
Run Code Online (Sandbox Code Playgroud)
是的,您可以根据需要加载任意数量的类
小智 6
您必须通过提供类名称的完全限定类名来加载类,其包路径为,
Class c = ucl.loadClass("com.mypackage.IndependentClass");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78992 次 |
| 最近记录: |