load class file from classpath

流过昼夜 提交于 2019-12-21 23:12:09

问题


I want to load class files from module dependencies (external jar files in the classpath). When I tried getResourceAsStream I got null pointer exception:

ClassParser parser = new ClassParser(this.getClass().getResourceAsStream("org/apache/tools/ant/taskdefs/optional/net/FTP.class"), "FTP.class");

Exception in thread "main" java.lang.NullPointerException
    at com.sun.org.apache.bcel.internal.classfile.ClassParser.<init>(ClassParser.java:101)
    at ParaNamesTest.printUtilsParNames(ParaNamesTest.java:52)
    at ParaNamesTest.main(ParaNamesTest.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

ant.jar on myclasspath but still java can't find it what should I do?


回答1:


You ask the class loader of your class (this.getClass()) for a resource from a different JAR, this won't work.

Try replacing ... (this.getClass().getResourceAsStream(... by ... (FTP.class.getResourceAsStream(... whith FTP being imported as org.apache.tools.ant.taskdefs.optional.net.FTP.

If you have the class name only at runtime, you can dynamically get a Class object by using the fully qualified class name and Class.forName:

String className = "org.apache.tools.ant.taskdefs.optional.net.FTP";
... (Class.forName(className).getResourceAsStream( ...



回答2:


If you getting null for this resource it means this class could not be found in your class path. I would try @Philipp's suggestion (not because its more likely to work) but because it will make it obvious if this class is on your class path.




回答3:


use Class.forName("java.lang.String") for example to get String.class



来源:https://stackoverflow.com/questions/7305195/load-class-file-from-classpath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!