Class ReflectionExamples
java.lang.Object
net.jrodolfo.java_evolution.java01.reflection.ReflectionExamples
Demonstrates reflection, introduced in Java 1.1.
The example keeps reflection declarations raw because generics were added later, in Java 5.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSimple target class used by the reflection examples. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptioncreateCommandByClassName(String className, String commandName) Creates an object through a constructor selected at runtime.Inspects a declared field without reading or changing its value.invokeMethodByName(Object target, String methodName, String argument) Invokes a method selected by name at runtime.runtimeTypeName(Object value) Reads the runtime type from an object reference.
-
Constructor Details
-
ReflectionExamples
public ReflectionExamples()
-
-
Method Details
-
runtimeTypeName
-
declaredFieldDescription
Inspects a declared field without reading or changing its value.- Returns:
- field name and type
- Throws:
NoSuchFieldException- when the field name is wrong
-
createCommandByClassName
public Object createCommandByClassName(String className, String commandName) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException Creates an object through a constructor selected at runtime.- Parameters:
className- fully qualified class name to loadcommandName- constructor argument- Returns:
- object created by reflection
- Throws:
ClassNotFoundException- when the class name cannot be loadedNoSuchMethodException- when the constructor signature is wrongInvocationTargetException- when the constructor throws an exceptionInstantiationException- when the class cannot be instantiatedIllegalAccessException- when access checks reject the call
-
invokeMethodByName
public String invokeMethodByName(Object target, String methodName, String argument) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException Invokes a method selected by name at runtime.- Parameters:
target- object receiving the method callmethodName- method to invokeargument- method argument- Returns:
- method result
- Throws:
NoSuchMethodException- when the method name or signature is wrongInvocationTargetException- when the invoked method throws an exceptionIllegalAccessException- when access checks reject the call
-