Reflection.java
package reflection;
import java.lang.reflect.Method;
public class Reflection {
private static <T> void test(Class<T> t) {
try {
//Get an instance
Object instance = t.newInstance();
//Get method
Method method = t.getMethod("test", String.class);
//Method execution
method.invoke(instance, "Wow!");
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
test(ReflectionTest.class);
}
}
class ReflectionTest {
public void test(String str) {
System.out.println(str);
}
}
result
Wow!
Well, what is it? Like accessing a PC remotely
Like accessing a class and accessing a method
It seems that you can also execute private methods if you use this
let's try it
I tried to make it private.java
class ReflectionTest {
private void test(String str) {
System.out.println(str);
}
}
result
java.lang.NoSuchMethodException: reflection.ReflectionTest.test(java.lang.String)
at java.lang.Class.getMethod(Unknown Source)
at reflection.Reflection.test(Reflection.java:14)
at reflection.Reflection.main(Reflection.java:25)
No! !! !! liar! !! !!
This seems to be necessary.java
package reflection;
import java.lang.reflect.Method;
public class Reflection {
private static <T> void test(Class<T> t) {
try {
//Get an instance
Object instance = t.newInstance();
//Get method
Method method = t.getDeclaredMethod("test", String.class);
//For private,I will access it, I need a declaration
method.setAccessible(true);
//Method execution
method.invoke(instance, "Wow!");
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
test(ReflectionTest.class);
}
}
class ReflectionTest {
@SuppressWarnings("unused")
private void test(String str) {
System.out.println(str);
}
}
It seems that you have to set true
in the setAccessible
method of the Method
class.
Well, this guy has access to the test class and private
It seems that you can do anything forcibly
I just don't understand There are exceptions like ReflectiveOperationException
As soon as you make a slight mistake, you will get various exceptions.
Well, it's really a force work
Recommended Posts