What is the best way to approximate class.getSimpleName () without loading the class?

Given the fully qualified class name that can be loaded using Class.forName (), is there a way to convert the name to what would be the result of loading the class and calling getSimpleName () without actually trying to load the class? I need this opportunity for thought.

+7
java reflection
source share
2 answers

I'm going to say that you cannot do this simply based on the name.

You can try to split by . and $ , but this code example shows that it is not always obvious where the simple name begins:

 class Ideone { private static class Bar {}; public static void main (String[] args) throws java.lang.Exception { class Foo$o { class Bar$bar {} }; class Foo$o$Bar { class Bar$bar {} }; class Foo$o$Bar$Bar$bar {} print(Ideone.class); print(Bar.class); print(Foo$o.class); print(Foo$o.Bar$bar.class); print(Foo$o$Bar.Bar$bar.class); print(Foo$o$Bar$Bar$bar.class); } private static void print(Class<?> clazz) { System.out.printf("fqn=%s, sn=%s%n", clazz.getName(), clazz.getSimpleName()); } } 

Output:

 fqn=Ideone, sn=Ideone fqn=Ideone$Bar, sn=Bar fqn=Ideone$1Foo$o, sn=Foo$o fqn=Ideone$1Foo$o$Bar$bar, sn=Bar$bar fqn=Ideone$1Foo$o$Bar$Bar$bar, sn=Bar$bar fqn=Ideone$2Foo$o$Bar$Bar$bar, sn=Foo$o$Bar$Bar$bar 

Ideone demo

i.e. if you said "name bit after the final $ or . ", you are mistaken.

The only convincing way to do this is to load the class, possibly without initializing it:

 Class<?> clazz = Class.forName(className, false, someClassLoadeR); 
+4
source share

As @AndyTurner’s answer shows, in all cases you cannot get a simple name from the class’s class string.

But if the restriction without trying to load the class does not prohibit reading the contents of the class file, you can do the following (for edge cases):

  • Get an InputStream for the contents of a class file through Class.getResourceAsStream()
  • Parse the beginning of the class file and read the name of the superclass from the constant pool.
  • (as @shmosel commented) Implement the logic of Class.getSimpleName() . The superclass name allows you to replace Class.getSimpleBinaryString() , which relies on an already loaded class.
0
source share

All Articles