在运行时从包中获取绝对类名

时间:2012-07-28 15:26:36

标签: java

如果我们有一个包名,请说.. com.google.foo.bar并且它有类似

的类
  

com.google.foo.bar.xyz

     

com.google.foo.bar.abc

     

如何在运行时获取这些名称?绝对地,我的意思是...包名+类名。那有什么用的吗?

1 个答案:

答案 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!/"

}