How to find the package name given a class name?

后端 未结 5 2040
我在风中等你
我在风中等你 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:45

     final Package[] packages = Package.getPackages();
        final String className = "ArrayList";
    
        for (final Package p : packages) {
            final String pack = p.getName();
            final String tentative = pack + "." + className;
            try {
                Class.forName(tentative);
            } catch (final ClassNotFoundException e) {
                continue;
            }
            System.out.println(pack);
            break;
        }
    

提交回复
热议问题