[JAVA] Power skills that can be used quickly at any time --Reflection

What is reflection?

Reflection is a group of APIs included in the Java standard library for handling meta information of classes, and is grouped in the java.lang.reflect package.

Reflection allows you to read a list of constructors, methods, and fields defined in a class, call methods from it, and retrieve field values. Normally, the procedure of directly creating an instance and calling a method without using reflection is sufficient, but with reflection, you can perform cheat techniques such as accessing invisible methods and changing final fields. Become.

What you can do with reflection

All types have a literal called .class. String.class gives you a Class class with information about the String class. The Class class includes methods for finding out what methods are defined in the target class, and methods for retrieving information on the defined fields. In addition, getClass () is defined in all classes as an instance method, and you can also use this method to get the Class class.

For example, the following will allow you to call the originally invisible methods defined in private.

//A class accessed by reflection.
public class Something {
  private String hoge() {
    return "hoge";

public class Main {
  public static void main(String[] args) {
    Something target = new Something();

    try {
      Class<Something> clazz = target.getClass();            //Since class is a reserved word, it is customary to use clazz or klass.
      Method method = clazz.getDeclaredMethod("hoge", null); //The second argument is an array of the argument types of the method to call. If not, set it to null
      method.setAccessible(true);                            //A magical method that makes a method that shouldn't be visible visible
      String result = (String) method.invoke(target, null);  //The instance that calls the method as the first argument, the actual argument after the second argument
      System.out.println(result);                            // "hoge"Is output
    } catch (NoSuchMethodException e) {
      //When there is no method that matches the method name specified in the character string
    } catch (InvocationTargetException e) {
      //When an exception occurs in the called method
    } catch (IllegalAccessException e) {
      //When accessing an inaccessible method

Be careful with reflection

When running a program that uses reflection, some VMs have strict rules for access by reflection. In that case, calling setAccessible (true) will throw a SecurityException. In addition, reflection specifies the names of all methods, classes, and fields as strings, so there is an exception if there is no match for that string. Therefore, when obfuscating the code with ProGuard etc., it is necessary to be careful about the code using reflection (because even if the field name or method name is changed, the character string is not changed). Also, unlike normal method calls, it goes through the reflection API, which inevitably affects performance.

Needless to say, you can forcibly access things that you cannot normally access, or you can rewrite the data, so please follow the dosage and use it correctly.

By the way, isn't there a lot of routine code?

I'll put them all together.


Recommended Posts

Power skills that can be used quickly at any time --Reflection
[ERROR message display] A simplified version that can be used at any time with the rails partial template.
Organize methods that can be used with StringUtils
[Ruby] Methods that can be used with strings
About the matter that hidden_field can be used insanely
Convenient shortcut keys that can be used in Eclipse
Summary of css selectors that can be used with Nookogiri
Create a page control that can be used with RecyclerView
Firebase-Realtime Database on Android that can be used with copy
Static analysis tool that can be used on GitHub [Java version]
Summary of ORM "uroboroSQL" that can be used in enterprise Java
I made a question that can be used for a technical interview
SwiftUI View that can be used in combination with other frameworks
Lock_version may be used for tables that tend to access and edit the same record at the same time
Java file input / output processing that can be used through historical background
Maybe it can be used at a year-end party? Mosaic game code
Simple slot machine implementation that can be used with copy and paste
[Rails] "pry-rails" that can be used when saving with the create method
Be aware of getting out of Rails beginners (* will be added at any time)
Performance analysis and failure diagnostic tools that can be used with OpenJDK
Ruby array methods that can be used with Rails (other than each)