本文介绍了确定一个类来自哪个 JAR 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我现在不在 IDE 面前,只是在查看 API 规范.
I am not in front of an IDE right now, just looking at the API specs.
CodeSource src = MyClass.class.getProtectionDomain().getCodeSource(); if (src != null) { URL jar = src.getLocation(); }我想确定一个类来自哪个 JAR 文件.是这样吗?
I want to determine which JAR file a class is from. Is this the way to do it?
推荐答案是的.它适用于除引导类加载器加载的类之外的所有类.另一种确定方法是:
Yes. It works for all classes except classes loaded by bootstrap classloader. The other way to determine is:
Class klass = String.class; URL location = klass.getResource('/' + klass.getName().replace('.', '/') + ".class");正如notnoop 指出的klass.getResource() 方法返回类文件本身的位置.例如:
As notnoop pointed out klass.getResource() method returns the location of the class file itself. For example:
jar:file:/jdk/jre/lib/rt.jar!/java/lang/String.class file:/projects/classes/pkg/MyClass$1.classgetProtectionDomain().getCodeSource().getLocation() 方法返回jar文件或CLASSPATH的位置
The getProtectionDomain().getCodeSource().getLocation() method returns the location of the jar file or CLASSPATH
file:/Users/home/java/libs/ejb3-persistence-1.0.2.GA.jar file:/projects/classes更多推荐
确定一个类来自哪个 JAR 文件
发布评论