如果我们有一个包名,请说.. com.google.foo.bar
并且它有类似
com.google.foo.bar.xyz
com.google.foo.bar.abc
。
如何在运行时获取这些名称?绝对地,我的意思是...包名+类名。那有什么用的吗?
答案 0 :(得分:1)
public String getSourceBase(Class<?> classx)
{
String cn = classx.getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = classx.getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}