从类路径加载类文件 [英] load class file from classpath

查看:80
本文介绍了从类路径加载类文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从模块依赖项(类路径中的外部jar文件)加载类文件。当我尝试getResourceAsStream时,出现空指针异常:

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)


b
$ b

ant.jar放在myclasspath上,但java仍然找不到我该怎么办?

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

推荐答案

您向您的类的类加载器( this.getClass())请求来自其他JAR的资源,这是行不通的。

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

尝试更换 ...(this.getClass()。getResourceAsStream(... ...(FTP.class.getResourceAsStream(... FTP 导入为 org.apache.tools.ant.taskdefs.optional.net.FTP

如果仅在运行时具有类名,则可以使用完整的变量来动态获取 Class 对象限定的类名和 Class.forName

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( ...

这篇关于从类路径加载类文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆