0

Trying to check if class K is a static class of A

class A {
    private static class K {
        static final int MODE1 = 1;
        static final int MODE2 = 2;
    }
}

Class<?> c = A.class;
for( Class<?> item: c.getDeclaredClasses() ) {
    if( Modifier.isStatic(item.getModifiers()) ) {
        if( "K".equals(item.getSimpleName()) ) {
            // found it!
        }
    }
}

Is this the only way? To iterate through all declared classes? For methods we have getDeclaredMethod(), for fields we have getDeclaredField(), but TTBOMK there is no getDeclaredClass() or something similar.

ilomambo
  • 8,290
  • 12
  • 57
  • 106

1 Answers1

2

Do you mean like this?

Class a = A.class;
Class k = Class.forName(a.getName()+"$K");

I don't imagine there is often done, so you might not have a more "friendly" method.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I don't know why it is not often required. In my case I define some static constants in static classes and I need to check it, in this specific case, through reflection. – ilomambo Jun 05 '13 at 07:21
  • I understand that this answers the question asked but I have a different case that this won't work for. I have instances of class objects passed to a method and I need to verify if the instance is of a static class or not. How would one do that? In that case, do I need to take the suggested approach in the original question and find if the class is enclosed in another class via the `getEnclosingClass()` method and then take it from there? – exbuddha Dec 10 '16 at 05:32
  • getEnclosingClass() is only needed for `enum`, if you do this for nested classes (including enum) you will get the class that is in or `null` if not in another. For `enum` I suggest looking at the getSuperClass() and if that is not `Enum` you have the actual `enum` class it was defined in. – Peter Lawrey Dec 10 '16 at 08:39