Day 1: Reflection in Java

102 阅读2分钟

其他可参考资料1

其他可参考资料2

其他可参考资料3

Day1 : Reflection in Java

What is Reflection

A program that can analyze the capabilities of classes is called reflection

Why we need Reflection

  • Analyze the capabilities of classes at runtime;
  • Inspect objects at runtime—for example, to write a single toString method that works for all classes;
  • Implement generic array manipulation code;
  • Take advantage of Method objects that work just like function pointers in languages such as C++.

Core.Java.Volume.I

1.Analyze the capabilities of classes at runtime

Before this, there are some prior knowledge we should know.

  • Runtime type identification(Java maintains to keep track of the class to which each object belongs)
  • Some syntax about deriving the class, method, and field

2.Inspect objects at runtime

Let's start with fields of objects. Although some fields may be private, we could use the setAccessible method, just like this

Employee li = new Employee("Li Feng",1984,12,24);
Class c1 = ;i.getClass();
Field f =c1.getDeclaredField("name");
f.setAccessible(true);
Object name = f.get(li)    // Now able to get he String Object "Li Feng"

3.Using Reflection to Write Generic Array Code

In some scenairos, we may have to create a generic array. For example, when one want to implement a copyOf method on his own, he may write like this

public static Object[] badCopyOf(Object[] a, int newLength) // not useful
{
 Object[] newArray = new Object[newLength];
 System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
 return newArray;
}

But that comes with a problem : the result array's type is Object, and we couldn't cast it to the Employee Class otherwise the virtual machine would generate a ClassCastExeption at runtime. That means we must make a new array of the same type as the original array.

Instead, we could do like this by utilizing the Reflection

public static Object goodCopyOf(Object a, int newLength) 
{
 Class cl = a.getClass();
 if (!cl.isArray()) return null;
 Class componentType = cl.getComponentType();
 int length = Array.getLength(a);
 Object newArray = Array.newInstance(componentType, newLength);
 System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
 return newArray;
}

4.Invoking Arbitary Methods

WE mainly achieve this by utilizing a method of Method

Object invoke(Object obj, Obj... args); //Its signature
// For a static method, the first para is ignored and you can set it to null

Here are something else to be noticed

  • Reflection is mainly to tool builders, not application programmers.
  • The Class class is actually a generic class
  • The getDeclaredFields, getDeclaredMethods, and getDeclaredConstructors methods of the Class class return arrays consisting of all fields, methods, and constructors that are declared in the class (without members of superclasses)

LearnGPT

Creating Objects with Reflection

To create an object with reflection, you must first get the Class object for the class that you want to create an object of. You can get the Class object by calling the getClass() method on an existing object, or by passing the class name to the Class.forName() method.

Once you have the Class object, you can create an instance of the class by calling the newInstance() method. This method creates a new instance of the class by invoking its default constructor. If the class does not have a default constructor, you can use the getConstructor() method to get a Constructor object and then call its newInstance() method to create an object with the desired constructor.

Handling Exceptions

Here are some common exceptions that may occur during Reflection:

  • IllegalAccessException: This exception occurs when you try to access a field, method or constructor that is not accessible from the current context.
  • IllegalArgumentException: This exception occurs when you pass an invalid argument to a method, constructor or field.
  • InvocationTargetException: This exception occurs when an exception is thrown by the method, constructor or field being invoked.
  • NoSuchFieldException: This exception occurs when you try to access a field that does not exist in the given class.
  • NoSuchMethodException: This exception occurs when you try to access a method that does not exist in the given class.

Design Patterns and Reflection

  • Proxy Pattern and Reflection

  • Decorator Pattern and Reflection

LOMBOK 's source code (To be continued)