黑马程序员技术交流社区
标题:
绝对牛的反射总结,看完必懂反射怎么使用
[打印本页]
作者:
嘎路的米
时间:
2015-6-29 20:51
标题:
绝对牛的反射总结,看完必懂反射怎么使用
/*
反射方法的总结。
看完该例子就会找到反射的规律
例如:
1,获取某类的构造函数,想都不用想,直接就上,Constructor constructor = 字节码文件对象.getConstructor();
这样就拿到了构造方法的Constructor对象。相对此构造方法怎么宰割,查API找方法去
2,获取某类的方法,想都不用想,直接就上,Method method = 字节码文件对象.getMethod("方法名",参数类型.class);
这样也拿到了方法的Method。想对此方法怎么宰割,继续查API去
3,如果方法是私有时,Method method = 字节码文件对象.getDeclaredMethod("方法名",参数类型.class);
然后再加上
method.setAccessible(true);
那么此私有的方法也获取到了,爱怎么使用再查API去。
*/
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
class Person {
public int x = 3;
private int y = 5;
public Person() {
System.out.println("person()....run");
}
public Person(int x, int y) {
System.out.println("Person(int x,int y).....run");
}
public void method() {
System.out.println("method()......run");
}
public void method(String str, int num) {
System.out.println("method(String str,int num)....run");
}
public static void staticMethod() {
System.out.println("staticMethod().....run");
}
private void privateMethod() {
System.out.println("privateMethod.....run");
}
}
public class Demo {
public static void main(String[] args) throws Exception {
// 获取无参构造函数
Constructor constructor1 = Class.forName("Person").getConstructor();
Person p = (Person) constructor1.newInstance();// person()....run
// 获取有参构造函数
Constructor constructor2 = Class.forName("Person").getConstructor(
int.class, int.class);
constructor2.newInstance(5, 6);// Person(int x,int y).....run
// 获取 公有 的字段
Field field1 = Class.forName("Person").getField("x");
int x = (Integer) field1.get(p);
System.out.println(x);// 3
// 获取 私有 的字段 ,getDeclaredField代表能够获取Person类中私有的字段
Field field2 = Class.forName("Person").getDeclaredField("y");
field2.setAccessible(true);// 想要获取就必须加上这一句
int y = (Integer) field2.get(p);
System.out.println(y);// 5
// 获取无参方法
Method method1 = p.getClass().getMethod("method", null);
method1.invoke(p, null);// method()......run
// 获取有参方法
Method method2 = p.getClass().getMethod("method", String.class,
int.class);
method2.invoke(p, "abc", 2);// method(String str,int num)....run
// 获取无参的静态方法
Method method3 = p.getClass().getMethod("staticMethod", null);
method3.invoke(p, null);// staticMethod().....run
// 获取 私有 的方法 ,getDeclaredMethod代表能够获取Person类中的私有方法
Method method4 = p.getClass().getDeclaredMethod("privateMethod", null);
method4.setAccessible(true);// 如果要获取私有的,就必须加上这一句
method4.invoke(p, null);// privateMethod.....run
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2