kimkevin
kimkevin

Reputation: 2222

How can I get declared classes in method?

This is Test class.

package com.reflection;

import com.reflection.test.A

public class Main {
  public void setA() {
    A a = new A();
  }
}

Then, I used ClassLoader for accessing and manipulating classes, fields, methods, and constructors as the code below

Class cls = cl.loadClass("com.reflection.Main");

Actually I really want to get A class by using cls and already tried to use getDeclaredClasses and getClasses but the result was nothing.

Upvotes: 1

Views: 594

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299108

You can't do that with pure Java reflection. Reflection will let you look at classes and their members, but not at the code inside a method.

The easiest thing to do is probably to do javap -v somewhere in the build process, parse the output for qualified class names and store them in a property file somewhere.

The harder version is to use a byte code tool like asm or ByteBuddy, write a visitor over all instructions in your class and store all classes from all instructions in a Map. While this is theoretically the elegant approach, it will probably be a nightmare.

Upvotes: 4

Related Questions