在了解反射之前需要弄清楚的几个基本概念
1.类类型(Class Type) ,所有的类都是Class类的实例对象;
2.关于静态加载与动态加载,编译时刻加载类是静态加载,运行时刻加载类是动态加载类,new创建的类都是在编译时刻加载好的类。编译之后集合的泛型是去泛型化的,也就是说java中集合的泛型,是防止错误输入的,只在编译阶段有效,绕过编译就无效了。
3.万事万物皆对象,方法也是对象,成员变量也是对象。
在了解过这些基本概念之后我们首先来用java反射机制做一个Hello World!
package test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class T170220_01 {
public static void main(String[] args) {
try {
//拿到A类的类类型
Class c = Class.forName("test.A");
//Class c1 = A.class;
//Method[] ms = c.getMethods();//getMethods 返回所有public方法包括继承方法
//输出变量列表
Field[] fs = c.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
System.out.println(fs[i].getName() + "[" + fs[i].getType().getName() + "]");
}
Method[] ms = c.getDeclaredMethods();//返回所有公共、保护、默认(包)访问和私有方法,但不包括继承方法
//输出方法列表
for (int i = 0; i < ms.length; i++) {
System.out.println(ms[i].getReturnType().getName() + " " + ms[i].getName());
ms[i].setAccessible(true);// 调用private方法的关键一句话
//ms[i].invoke(c.newInstance());
}
Method method = c.getMethod("say",String.class);//方法名和参数列表组成方法签名 -> String name, Class<?>... parameterTypes
method.invoke(c.newInstance(),"Hello World!");//类的实例并输入参数值
System.out.println("-----------------去泛型化-----------------");
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
Method m = list.getClass().getMethod("add", Object.class);
m.invoke(list, "hello");//对去泛型化的集合添加一个非Integer的字符串
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
class A{
public String f1;
private int f2;
protected double f3;
public void m1(){
System.out.println("this is function m1");
}
private void m2(){
System.out.println("this is function m2");
}
protected void m3(){
System.out.println("this is function m3");
}
void m4(){
System.out.println("this is function m4");
}
public void say(String hello){
System.out.println(hello);
}
}
输出结果
f1[java.lang.String]
f2[int]
f3[double]
void say
void m1
void m2
void m3
void m4
Hello World!
-----------------去泛型化-----------------
1
2
hello