MENU

Java Reflection Made Easy

TOC

Java Reflection Made Easy

java(at sentence-end, falling tone) indicates a confident conclusionreflectionIntroducing utility classes for easy access to the API.

What is reflection?

Reflection APIis the "thejava.lang.reflect” included in the package,
This is an API that retrieves information such as fields and methods from Java classes.
The following classes are mainly used.

  • Class
  • Constructor
  • Method
  • Field

reflectionBy using , you can create classes or call methods without having to code them directly.
You can create a class instance from a string or execute a method.

By writing the definitions of class names and method names in external files such as XML, you can dynamically adapt the application to changes in the environment during runtime.
It is also a very effective API for building highly flexible applications.


Purpose of Reflection

reflectionis not often used directly by users,
It is widely used in web applications such as Struts and frameworks such as O/R mapping.

For example, when automatically setting web screen input data to JavaBeans properties,
It is used when issuing SQL that automatically updates based on JavaBeans properties.

In addition, functions such as dynamically loading and registering plug-ins that extend functionality at application startup arereflectionThis can be easily achieved by using the

Sample Execution

Now, please run the sample and experience framework-like programming.

The following classes are used herereflectionIt shows a simple way to use the utility.

Main.java... Class to execute
BeanUtil.javaUtility class for reflection
FreeSoft.javaThe class representing FreeSoff is used as a reflection.

When executed as usual

System.out.println(">>> Normal case.");
FreeSoft freeSoft = new FreeSoft();
freeSoft.setName("Chat&Messenger Chat and Messenger!!!");
freeSoft.showName(); freeSoft.
freeSoft.showPrice(0); freeSoft.

When executed using reflection

System.out.println(">> >> When reflection is used"));
// Instance creation of the FreeSoft class
Object invokeObject = BeanUtil.newInstance("FreeSoft"));
// Set a value in the name field.
BeanUtil.setProperty(invokeObject,. "name". , "Chat&Messenger Chat and Messenger!");
// FreeSoft's showName() method.
BeanUtil.invoke(invokeObject, invoke "showName"., null);
// Execute FreeSoft's showPrice() method.
// If the method has arguments, they must be passed in an array of type Object.
BeanUtil.invoke(invokeObject, invoke "showPrice".,new Object[]{new Integer(0)});

Execution Result

The execution result is the same in the normal case and when reflection is used.

>>> Normal case

Software name: Chat&Messenger Chat and Messenger!

Price : 0 yen

>> >> When using reflection

Software name: Chat&Messenger Chat and Messenger!

Price : 0 yen

BeanUtil method details

newInstance

public static Object newInstance(String className)
                                    throws Exception
Creates and returns an instance from the string "className".

Parameters: A
className - fully qualified class name
Return value: 1
New instances of fully qualified class names
Exceptions: The
Exception

newInstance

public static Object newInstance(String className,
                                           Object[] argObj)
                                    throws Exception
Creates and returns an instance from the string "className".

Parameters: A
className - fully qualified class name
argObj - Constructor Arguments
Return value: 1
New instances of fully qualified class names
Exceptions: The
Exception

newInstance

public static Object newInstance(Class clazz)
                                    throws Exception
Creates and returns an instance from the class "clazz".

Parameters: A
clazz - class
Return value: 1
New instances of clazz
Exceptions: The
Exception

newInstance

public static Object newInstance(Class clazz,
                                           Object[] argObj)
                                    throws Exception
Creates and returns an instance from the class "clazz".

Parameters: A
clazz - class
argObj - Constructor Arguments
Return value: 1
New instances of clazz
Exceptions: The
Exception

setProperty

public static void setProperty(Object invokeObject, String fieldName, String
                               String fieldName, Object value)
                               Object value)
                        throws Exception
Call the setter method of the field "fieldName" of the object "invokeObject" and store the value "value".

If there is no setter method, the value will be set directly to the field. However, in this case, the access modifier of the target property must be public.

Parameters: A
invokeObject - Objects to be executed
fieldName - Property name of the object to be executed
value - Value to be set
Exceptions: The
Exception - The following exceptions occur
InvocationTargetException - If the underlying method throws an exception
IllegalAccessException – This Method object is Java
When language access control is implemented and the underlying method cannot be accessed
NoSuchMethodException - If the method with the specified name is not found

getProperty

public static Object getProperty(Object invokeObject, String fieldName)
                                           String fieldName)
                                    throws Exception
Calls the getter method of the field fieldName of the object invokeObject to obtain the value.
If there is no getter method, the value will be retrieved directly from the field. However, in this case, the access modifier of the target property must be public.

Parameters: A
invokeObject - Objects to be executed
fieldName - Property name of the object to be executed
Return value: 1
Return value of getter method
Exceptions: The
Exception - The following exceptions occur
InvocationTargetException - If the underlying method throws an exception
IllegalAccessException – This Method object is Java
When language access control is implemented and the underlying method cannot be accessed
NoSuchFieldException - If the field with the specified name is not found

invoke

public static Object invoke(Object invokeObject, String callMethod, String
                                      String callMethod, String
                                      Object[] argObjects)
                               throws InvocationTargetException, IllegalAccessException, and
                                      IllegalAccessException, NoSuchMethodException
                                      NoSuchMethodException
Executes the method "callMethod" of the object "invokeObject".
If there is a return value, it can be obtained as an Object.

Parameters: A
invokeObject - Objects to be executed
callMethod - Name of method to be executed
argObjects - If there is an argument, pass it as an array of objects. If there are no arguments, pass null.
Return value: 1
Return value of "callMethod" executed
Exceptions: The
InvocationTargetException - If the underlying method throws an exception
IllegalAccessException – This Method object is Java
When language access control is implemented and the underlying method cannot be accessed
NoSuchMethodException - If the method with the specified name is not found

findMethod

public static Method findMethod(Object invokeObject, String callMethod, String
                                                  String callMethod, String
                                                  Object[] argObjects)
                                           throws NoSuchMethodException
Searches for the method "callMethod" of the object "invokeObject".

Parameters: A
invokeObject - Objects to be executed
callMethod - Method name of the object to be executed
argObjects - If there is an argument, pass it as an array of objects. If there are no arguments, pass null.
Return value: 1
Method object matching the specified argument condition
Exceptions: The
NoSuchMethodException - If no matching method is found, or if the name is "" or "".

setField

public static void setField(Object invokeObject, String fieldName, String
                            String fieldName, Object value)
                            Object value)
                     throws IllegalAccessException, NoSuchFieldException
                            NoSuchFieldException
Stores the value "value" in the field name "fieldName" of the object "invokeObject" to be executed.

Parameters: A
invokeObject - Objects to be executed
fieldName - Field name of the object to be executed
value - Value to be set
Exceptions: The
IllegalAccessException – The field on which the specified object is based (or its subclass or implementer)
is not an instance of the class or interface it declares, or if the unwrapping conversion fails
NoSuchFieldException - If the field with the specified name is not found

getField

public static Object getField(Object invokeObject, String fieldName)
                                        String fieldName)
                                 throws IllegalAccessException, NoSuchFieldException
                                        NoSuchFieldException
Obtains the value of the field name "fieldName" of the object "invokeObject" to be executed.

Parameters: A
invokeObject - Objects to be executed
fieldName - Field name of the object to be executed
Return value: 1
return value
Exceptions: The
IllegalAccessException – The field on which the specified object is based (or its subclass or implementer)
is not an instance of the class or interface it declares, or if the unwrapping conversion fails
NoSuchFieldException - If the field with the specified name is not found

hasField

public static boolean hasField(Object object,
                               String fieldName)
                        throws Exception
Check if the object "object" declares the field name "fieldName".

Parameters: A
object - Objects to be inspected
fieldName - Name of field to be inspected
Return value: 1
true if declared
Exceptions: The
Exception

getAllFields

public static java.util. getAllFields(Object object)
                                      throws Exception
Parameters: A
object
Return value: 1
Exceptions: The
Exception

getShortClassName

public static String getShortClassName(Object object)
Obtains the fully unqualified class name from the object.

Parameters: A
object
Return value: 1

getShortClassName

public static String getShortClassName(String className)
Get the class name from the fully qualified name.

Parameters: A
className
Return value: 1

getFieldName

public static String getFieldName(String methodName)
Change the field name from the method name. Must conform to JavaBeans conventions.

Parameters: A
methodName
Return value: 1

isClassExist

public static boolean isClassExist(String className)
Verifies whether the fully qualified name "className" is an existing class name.

Parameters: A
className
Return value: 1

getPropertyDescriptors

public static PropertyDescriptor[]. getPropertyDescriptors(Object object)
                                                              throws IntrospectionException
Returns a PropertyDescriptor holding object information for "object".

Parameters: A
object
Return value: 1
Exceptions: The
IntrospectionException

BeanUtil Source Code

TOC