Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving class inside a method using reflection

class test {
    public static void main(String[] args) {
         new test();
    }
    void method() {
         class inside {
              int a;
              void methodinside() {}
         }
    }
}

I was declaring class using reflection like:

Class c = Class.forName("test");
Class[] cls = c.getDeclaredClasses();
for(Class cl : cls)
     System.out.println(cl.getName());

but, my program cannot find class inside.

like image 755
newbie Avatar asked Apr 16 '15 02:04

newbie


People also ask

Which is the way to get the object of class class in reflection?

Object. getClass() If an instance of an object is available, then the simplest way to get its Class is to invoke Object. getClass() .

How do you find the instance of a class using reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.

Can you put a class inside a Method?

In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.

How do you access a private Method using reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.


1 Answers

I don't think there is a method to find local classes (classes defined inside a method).

You could try to enumerate all classes in the package and then use getEnclosingClass (the opposite of what you are looking for) to filter them.

like image 54
Thilo Avatar answered Oct 13 '22 22:10

Thilo