Test empty method body with Java Reflection
As the title suggests, is there any way to see if a method has an em开发者_如何学JAVApty body using reflection?
With reflection, I don't think so. You could look into BCEL though...
The Byte Code Engineering Library is intended to give users a convenient possibility to analyze, create, and manipulate (binary) Java class files
Here is a snip that might get you started from this article...
public class ClassViewer{
private JavaClass clazz;
public ClassViewer(String clazz){
this.clazz = Repository.lookupClass(clazz);
}
public static void main(String args[]){
if(args.length != 1)
throw new IllegalArgumentException(
"One and only one class at a time!");
ClassViewer viewer = new ClassViewer(args[0]);
viewer.start();
}
private void start(){
if(this.clazz != null){
// first print the structure
// of the class file
System.err.println(clazz);
// next print the methods
Method[] methods = clazz.getMethods();
for(int i=0; i<methods.length; i++){
System.err.println(methods[i]);
// now print the actual
// byte code for each method
Code code = methods[i].getCode();
if(code != null)
System.err.println(code);
}
}else
throw new RuntimeException(
"Class file is null!");
}
}
No, you can't inspect that actual (byte-)code of any given method using reflection.
That kind of information isn't available via usual reflection API, which retrieves class and instance variables, method signatures, etc., but not actual bytecode.
You could use a library:
JavaAssist
- http://www.csg.is.titech.ac.jp/~chiba/javassist/
BCEL
- http://jakarta.apache.org/bcel/
You will probably need to use "Java agents". There shouldn't be any reasonable excuse to do this sort of thing. Having said that, typical implementations of the JVM itself will do this sort of thing to ignore finalizable objects.
精彩评论