Rustom
Rustom

Reputation: 31

Getting inner class type name

I'm trying to get the name of a type (which is an interface) that is instantiated within a class but the available methods I've tried do not return the actual name of the type.

Example:

To get the name I would do:

class Test {

    void test(Object o) {
        System.out.println(o.getClass());
    }

}

Taking the java.lang.Runnable interface for example:

...
test(new Runnable() {});

Would print out something like class test.Test$2, I've tried other methods in the Class class but they just print out null or test.Test. How would I be able to get class java.lang.Runnable from it?

Thanks!

Upvotes: 0

Views: 140

Answers (2)

nanofarad
nanofarad

Reputation: 41281

For an inner anonymous class, you can do as follows:

void test(Object o) {
    if(o.getClass().isAnonymousClass()) {
      System.out.println(o.getClass().getInterfaces()[0].getName());
    } else {
      System.out.println(o.getClass().getName());
    }        
}

Upvotes: 1

Emil L
Emil L

Reputation: 21081

You could do this by simply doing an instanceof check:

void test(Object o) {
    System.out.println(o instanceof Runnable);
}

This will print true in case the object implements the Runnable interface.

If you want a more dynamic solution (for instance if you wanted to print all the interfaces of the Object o ) you'd have to do something like:

void test(Object o) {
    for (Class i : o.getClass().getInterfaces()) {
        System.out.println(i.getName());
    }
}

Upvotes: 0

Related Questions