How to find the package name given a class name?

后端 未结 5 2067
我在风中等你
我在风中等你 2020-12-19 03:20

Given a class name as a string, how do I get the package name of it at run time ? I do not have the fully qualified name with package name + class name. Simply only the clas

5条回答
  •  轮回少年
    2020-12-19 03:41

    This is most likely an incredibly inefficient, bloated, inconvenient way of doing what you're trying to achieve, and hopefully there's already an out-of-the-box, single way to do it... but it should work.

    Basically, scan through every class in the class path, until you find a class where getSimpleName() matches the class name you have.

    I recommend looking at Google Classpath Explorer to help manage the nuts and bolts of doing this.

    It could look something like this:

     ClassPath classpath = new ClassPathFactory().createFromJVM();
     RegExpResourceFilter regExpResourceFilter = new RegExpResourceFilter(".*", ".*\\.class");
     String[] resources = classpath.findResources("", regExpResourceFilter);
    

    resources is an array of Strings like 'com/foo/bar/Baz.class'. You can now simply loop through and find matching entries, and transform them from slashed to dotted, strip out '.class', etc. Just be careful around trying to match inner classes, as they will have a '$' character in them.

    Also, as far as I am aware, this will NOT cause those classes to be loaded.

提交回复
热议问题