BufBills
BufBills

Reputation: 8103

Retrieving an object's class name using reflection

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;

public class TryReflection {

    public TryReflection() {
        int a = 0;
    }

    public static int getMax() {

        int max = 0;
        return max;
    }

    public static void main(String[] args) {

        TryReflection myObject = new TryReflection();

        int ret = myObject.getMax();
        System.out.printf("max is %d\n", ret);

        Method[] methods = myObject.class.getMethods();
        // for(Method method:methods) {
        // System.out.println("method = " + method.getName());
        // }

    }

}

I don't understand why do I get the following error when I compile the above code.

TryReflection.java:31: error: cannot find symbol
    Method[] methods = myObject.class.getMethods();
                       ^
  symbol:   class myObject
  location: class TryReflection
1 error

Upvotes: 0

Views: 2175

Answers (2)

Sandeep Chatterjee
Sandeep Chatterjee

Reputation: 3247

Since you have an instance of your object available, you need to use myObject.getClass()

TryReflection myObject = new TryReflection();

int ret = myObject.getMax();
System.out.printf("max is %d\n", ret);

Method[] methods = myObject.getClass().getMethods();
for (Method method : methods) {
    System.out.println("method = " + method.getName());
}

Please refer the official tutorials for more details.

Upvotes: 1

Kevin Coppock
Kevin Coppock

Reputation: 134664

myObject is an instance of a class, so you should use myObject.getClass(). Alternatively just call TryReflection.class.

Upvotes: 1

Related Questions