Java has a feature called reflection to get the type information of an object. I knew the name and outline so far, but I wanted to know it properly, so I will summarize it.
Java allows you to dynamically retrieve and manipulate type information at runtime. In information engineering, the technology of reading or rewriting the structure of the program itself in the process of executing the program is called reflection. Java reflection mainly provides the following functions.
Freywork and others use this reflection to access fields and call methods.
The Java reflection mechanism is made possible by utilizing the following two classes and functions.
java.lang.Class
java.lang.Class
Java provides a class called java.lang.Class
that represents a class. Each class or interface handled in the source code has a corresponding Class object. This is expressed as Class <String>
for String, for example.
This class is special and cannot be instantiated using new
etc. Instead, it is generated by the JVM when loading the class, or built automatically by calling the class loader's defineClass method.
In Java, it is possible to get type information from the generated Class object.
A class loader is an object that literally has the role of loading a class. When you get the Class object from the source code, you get it internally from this class loader.
It's so easy, but I'd like to use reflection. First, prepare the following simple class.
public class Foo {
Foo(String name){
this.name = name;
}
private String name;
public void greet(){
System.out.println("Hello, " + name);
}
}
Let's call Foo # greet ()
using reflection on the above Foo.class
class.
import java.lang.reflect.Method;
public class ReflectionSample {
public static void main(String[] args) {
Class<Foo> fooClazz1 = Foo.class;
Foo foo = new Foo("taro");
try {
Method greetMethod = fooClazz1.getMethod("greet");
greetMethod.invoke(foo);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
}
A method call for a class is made using java.lang.reflect.Method # invoke
.
The Method
class can be obtained from Class # getMethod
. In that case, specify the method name you want to call.
This time Foo # greet ()
has no argument, but you can pass the argument of the method to be called after the second argument.
Execution result
Hello, taro
I don't usually use it when writing business applications, but I thought that I might have some knowledge about this when reading framework code.
Recommended Posts