how whoAmI() access the name of the type from which it is called?
You can access the superclass using Class.getSuperclass() :
void whoAmI() { Class superclass = getClass().getSuperclass(); String superclassText = "no superclass found"; if (superclass != null) superclassText = superclass.getName(); System.out.println(superclassText); }
This technically answers your question, but only because I suggested that the method we are discussing belongs to the superclass (which it does in your example).
But perhaps you really want to know the answer to "How can a method determine which class is defined, even if it is called on an instance of a subclass?" That would be a much more complicated question. While java.lang.reflect.Method.getDeclaringClass() seems to do what you ask, you first need to declare an instance of the Class class (i.e. SuperTest.class ) that wins the item - if you had was that you would not need to use java.lang.reflect.Method at all.
However, if I can change the premise a bit, suppose you insert each class with a static instance of the class as follows:
private final static Class THIS_CLASS = SuperTest.class;
Then it becomes possible to write a method that does not access the declaring class by name, since it can assume that whatever class it gets in brackets will have THIS_CLASS :
void whoAmI() { final String myName = "whoAmI"; final Class[] myParamTypes = {}; String result; try { Method thisMethod = THIS_CLASS.getDeclaredMethod(myName, myParamTypes); result = "I am " + thisMethod.getDeclaringClass().getName() + "." + myName + Arrays.toString(myParamTypes); // Now swap the square brackets from Arrays.toString for parentheses result = result.replaceAll("\\[", "\\(").replaceAll("\\]", "\\)"); } catch (NoSuchMethodException | SecurityException ex) { result = ex.toString(); } System.out.println(result); }
This will exit I am packagename.MinsSuperTest.whoAmI() .
muffin
source share