一、定义一个需要访问的类
package Reflect;
public class Base extends Father implements Inter {
private String no ="tyler";
public Base(){
}
public Base(String no){
this.no = no;
}
public String say(String say){
return say;
}
public String getno() {
return no;
}
public void setno(String no) {
this.no = no;
}
}
二、测试
package Reflect;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class TestReflect {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//通过实例对象获取类名
Base base = new Base();
System.out.println(base.getClass().getName());
Class<?> cla = Class.forName("Reflect.Base"); //调用的是无参构造函数
System.out.println(cla.getName());
Class clazz = Base.class;
System.out.println(clazz.getName());
//通过Class实例化其他类对象
Base bs1 = base.getClass().newInstance();
Base bs2 = (Base)cla.newInstance();
Base bs3 = (Base)clazz.newInstance();
System.out.println(bs1.getno()+bs2.getno()+bs3.getno());
//突然想到的一个运算符的问题
System.out.println(4+5+"6"); //结果96
System.out.println("6"+4+5); //结构645
//获取构造函数
Constructor<?> cons[]=clazz.getConstructors();
Base be1 = (Base) cons[0].newInstance();
Base be2 = (Base) cons[1].newInstance("Lucy");
System.out.println(be1.getno()+be2.getno());
Class<?> p[]=cons[1].getParameterTypes();//获取参数
int mo=cons[1].getModifiers();//获取方法修饰符
System.out.println(Modifier.toString(mo)+" ");
System.out.println(p[0].getName());
//获取接口
Class<?> intes[]=clazz.getInterfaces();
for (int i = 0; i < intes.length; i++) {
System.out.println("实现的接口 "+intes[i].getName());
}
//获取父类
Class<?> fathers = clazz.getSuperclass();
System.out.println("唯一的父类"+fathers.getName());
//获取属性
Field field = clazz.getDeclaredField("no");
field.setAccessible(true);
Base obj = (Base)clazz.newInstance();
field.set(obj, "Mark");
System.out.println(field.get(obj));
//修改数组信息
int[] temp={1,2,3,4,5};
Class<?> demo = temp.getClass().getComponentType();
System.out.println("数组的第一个元素: "+Array.get(temp, 0));
System.out.println("数组长度 "+Array.getLength(temp));
Array.set(temp, 0, 100);
System.out.println("修改之后数组第一个元素为: "+Array.get(temp, 0));
System.out.println("数组长度 "+Array.getLength(temp));
//调用方法
Method method = clazz.getMethod("say",String.class);
System.out.println(method.invoke(obj,"say"));
}
}