vendredi 29 juillet 2016

Which Class method generates the right input for Class.forName()?

I would like to write some code like this:

Object o = ...;
String oTypeName = o.getClass().getName();

//on the other side of the wire:

Class<?> oClass = Class.forName(oTypeName);
Object oAgain = oClass.newInstance();

However, it's not clear from the javadoc which method I should use to initialize oTypeName, i.e. which method will produce the expected input to Class.forName():

  • getCanonicalName(): "Returns the canonical name of the underlying class as defined by the Java Language Specification. Returns null if the underlying class does not have a canonical name (i.e., if it is a local or anonymous class or an array whose component type does not have a canonical name)."
  • getName(): "Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String. If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by The Java™ Language Specification."
  • getTypeName(): "Return an informative string for the name of this type."

It's fairly obvious that I don't want either of these:

I don't expect this to work for primitive types. It's okay if it won't work for arrays. The main thing I'm concerned about is inner classes and Foo.Bar vs. Foo$Bar.





Aucun commentaire:

Enregistrer un commentaire