如果有一个名为“demo.class”的类文件, 是否可以在不运行VM的情况下分析文件,然后获取 其成员的消息,例如属性'名称,方法'名称和字段'类型?
如果有,请给我任何关于如何开始工作的建议,谢谢!
答案 0 :(得分:3)
您可以使用反射
http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Member;
import static java.lang.System.out;
enum ClassMember { CONSTRUCTOR, FIELD, METHOD, CLASS, ALL }
public class ClassSpy {
public static void main(String... args) {
try {
Class<?> c = Class.forName(args[0]);
out.format("Class:%n %s%n%n", c.getCanonicalName());
Package p = c.getPackage();
out.format("Package:%n %s%n%n",
(p != null ? p.getName() : "-- No Package --"));
for (int i = 1; i < args.length; i++) {
switch (ClassMember.valueOf(args[i])) {
case CONSTRUCTOR:
printMembers(c.getConstructors(), "Constructor");
break;
case FIELD:
printMembers(c.getFields(), "Fields");
break;
case METHOD:
printMembers(c.getMethods(), "Methods");
break;
case CLASS:
printClasses(c);
break;
case ALL:
printMembers(c.getConstructors(), "Constuctors");
printMembers(c.getFields(), "Fields");
printMembers(c.getMethods(), "Methods");
printClasses(c);
break;
default:
assert false;
}
}
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
}
}
private static void printMembers(Member[] mbrs, String s) {
out.format("%s:%n", s);
for (Member mbr : mbrs) {
if (mbr instanceof Field)
out.format(" %s%n", ((Field)mbr).toGenericString());
else if (mbr instanceof Constructor)
out.format(" %s%n", ((Constructor)mbr).toGenericString());
else if (mbr instanceof Method)
out.format(" %s%n", ((Method)mbr).toGenericString());
}
if (mbrs.length == 0)
out.format(" -- No %s --%n", s);
out.format("%n");
}
private static void printClasses(Class<?> c) {
out.format("Classes:%n");
Class<?>[] clss = c.getClasses();
for (Class<?> cls : clss)
out.format(" %s%n", cls.getCanonicalName());
if (clss.length == 0)
out.format(" -- No member interfaces, classes, or enums --%n");
out.format("%n");
}
}
答案 1 :(得分:1)
如果您只有类文件(并且因为它不在类路径中而无法加载它,或者您不想加载它),您可以使用Apache Commons Byte Code Engineering Library
进行检查。ClassParser parser=new ClassParser(getClass().getResourceAsStream("/my/package/MyClass.class"), "MyClass.class");
JavaClass javaClass=parser.parse();
javaClass.getMethods(); // Get whatever info you need
答案 2 :(得分:0)
你可以使用Java反汇编程序'javap命令'
假设您的班级文件位于bin文件夹&amp;路径是 “d:\ dev的\ jdk_1.06 \ BIN” 然后 1.打开命令提示符 2.将目录更改为上述路径。 3.type java javaclassfilename 例如:for hello.class 使用命令javap hello