Testing the empty body of a method using Java Reflection

As the name suggests, is there a way to see if a method has an empty body using reflection?

+4
source share
4 answers

Thinking, I don’t think so. You can watch BCEL though ...

The engineering byte code library is designed to provide users with a convenient way to parse , create, and manipulate (binary) Java class files

Here is a piece that could start with 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!"); } } 
+4
source

No, you cannot verify this actual (byte) code of any given method using reflection.

+1
source

Such information is not available using the regular reflection API, which extracts class and instance variables, method signatures, etc., but not the actual bytecode.

You can use the library:

Javaassist

BCEL

0
source

You will probably have to use Java Agents. There should be no reasonable excuse for doing such things. Having said that, typical JVM implementations themselves will do such things to ignore the final objects.

0
source

Source: https://habr.com/ru/post/1338261/


All Articles