středa 18. května 2016

How to get fully qualified name of Java class from .class file

I was creating a utility that uploads java classes using web browser to runtime environment. The problem was how to get fully qualified name of class when I obtain just the .class file without information about path of packages. For example imagine we have com.company.MyCustom class, the class is uploaded via web browser to application server as a MyCustom.class file without any information about packages. But the server has to know the packaging directory structure to store the .class file properly to classpath.

I studied the .class file internal structure to obtain the class name including packages from the content of the .class file. The structure is very well documented is the specification here: https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html , but it shows little bit troublesome to parse the file in pure Java. 

Finally I found the Apache Common BCEL (http://commons.apache.org/proper/commons-bcel/manual.html) project. It is much wider that I need and contains also ability to obtain the full class name from class using 3 lines of code:

FileInputStream input = new FileInputStream(new File("MyCustom.class")); ClassParser parser = new ClassParser(input,classname);
JavaClass javaClass = parser.parse();
String fullClassname = javaClass.getClassName();

Really easy isn't it?




Žádné komentáře:

Okomentovat