1
votes

I want to get package name from a .class file, but after trying to use org.apache.bcel, I am not satisfied with it because there are always some classes which can not be parsed.

the rate is about 20 over 500.

So, is there any other library which can get the package name from a class file?

Edit: this is how I get a package name from a class file now. This can achieve my goal, but some class files can not be parsed, so I want to know is there a better way.

import org.apache.bcel.classfile.ClassParser;

        String filePath = "/tmp/Test.class"
        ClassParser classParser = new ClassParser(filePath);

        JavaClass javaClass;
        try {
            javaClass = classParser.parse();
        } catch (IOException | ClassFormatException e) {
            System.out.println(filePath);
        }

        String packageName = javaClass.getPackageName();
Are you parsing actual .class files or MyObject.class using reflection - Mark
In Java or how do you want to get the package name? What are you doing right now? Show the code please. getPackage() of a Class object should return the Package. Calling getName() on it return the name. - UninformedUser
@Mark I am parsing actual .class files - ruiruige1991
@AKSW to do that, one would first have to load the class. If the class file does not reside in the class path, one would have to create a new ClassLoader for that. Still, that's all possible and probably worth a try. - OhleC
@user3978288 to clarify: Are you talking about cases where classParser.parse() throws an exception? If so, which one (and with what message)? - OhleC