1.java反射机制概述
加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,我们形象的称之为:反射。

@Testpublic void test() throws Exception {Class clazz= Person.class;//1.通过反射,创建Person类的对象Constructor cons=clazz.getConstructor(String.class,int.class);Object obj=cons.newInstance("Tom",12);Person p=(Person)obj;System.out.println(p.toString());//2.通过反射,调用对象指定的属性和方法Field age = clazz.getDeclaredField("age");age.set(p,10);System.out.println(p.toString());Method show = clazz.getDeclaredMethod("show");show.invoke(p);System.out.println("***************************");}
2.关于java.lang.Class类的理解
(1)类的加载过程:程序在经过javac.exe命令以后,会生成一个或多个字节码文件(.class结尾),接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件加载到内存中,此过程就称为类的加载。加载到内存中的类称为运行时类,此运行时类,就作为Class的一个实例。
(2)换句话说,Class的实例就对应着一个运行时类。
(3)加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式来获取此运行时类。
3.获取Class类的实例
//获取Class类的实例@Testpublic void test1() throws ClassNotFoundException {//方式一:调用运行时类的属性:classClass clazz1=Person.class;System.out.println(clazz1);//方式二:通过运行时类的对象,调用getClass()Person p1=new Person();Class clazz2=p1.getClass();System.out.println(clazz2);//方式三:调用Class的静态方法:forName(String classpath)Class clazz3 = Class.forName("day15.Person");System.out.println(clazz3);//使用类的加载器(了解)ClassLoader classLoader = ReflectionTest.class.getClassLoader();Class clazz4=classLoader.loadClass("day15.Person");System.out.println(clazz4);}
4.创建运行时类的对象
通过反射创建对应的运行时类的对象
@Testpublic void test() throws IllegalAccessException, InstantiationException {Class clazz=Person.class;/*** newInstance():调用此方法,创建运行时类的对象,内部调用了运行时类的空参构造器* 要想此方法正常的创建运行时类的对象,要求:* 1.运行时类必须提供空参的构造器* 2.空参的构造器的访问权限得够,通常设置为public* 在javabean中要求提供一个public的空参构造器。原因:* 1.便于通过反射,创建运行时类的对象* 2.便于子类继承此运行时类时,默认调用super()时,保证父类哟此构造器*/Person obj = clazz.newInstance();//调用Person类的空参构造器System.out.println(obj);}
(1)获取当前运行时类的属性结构:
public class FieldTest {@Testpublic void test(){Class clazz=Person.class;//获取属性结构//getFields():获取当前运行时类及其父类中声明为public访问权限的属性Field[] fields = clazz.getFields();for(Field field:fields){System.out.println(field);}System.out.println("**************************");//getDeclaredFields():获取当前运行时类中声明的所有属性。(不包含父类中声明的属性)Field[] declaredFields = clazz.getDeclaredFields();for (Field f:declaredFields){System.out.println(f);}}//权限修饰符 数据类型 变量名@Testpublic void test1(){Class clazz=Person.class;Field[] declaredFields = clazz.getDeclaredFields();for (Field f:declaredFields){//1.权限修饰符int modifiers = f.getModifiers();System.out.print(Modifier.toString(modifiers)+"\t");//2.数据类型Class type = f.getType();System.out.print(type.getName()+"\t");//3.变量名String name = f.getName();System.out.print(name);System.out.println();}}
}
(2)获取运行时类的方法结构:
public class MethodTest {@Testpublic void test(){Class clazz=Person.class;//getMethods():获取当前运行时类及其所有父类中声明为public权限的方法Method[] methods = clazz.getMethods();for(Method m:methods){System.out.println(m);}System.out.println();//getDeclaredMethods():获取当前运行时类中声明的所欲方法(不包含父类中声明的方法)Method[] declaredMethods = clazz.getDeclaredMethods();for(Method m:declaredMethods){System.out.println(m);}}/*** @Xxxx* 权限修饰符 返回值类型 方法名(参数类型1 形参名1,...)throws XxxException{}*/@Testpublic void test1(){Class clazz=Person.class;Method[] methods = clazz.getMethods();for(Method m:methods){//1.获取方法声明的注解Annotation[] annotations = m.getAnnotations();for(Annotation a:annotations){System.out.println(a);}//2.权限修饰符int modifiers = m.getModifiers();System.out.print(Modifier.toString(modifiers)+"\t");//3.返回值类型System.out.print(m.getReturnType().getName()+"\t");//4.方法名System.out.print(m.getName());System.out.print("(");//5.形参列表Class[] parameterTypes = m.getParameterTypes();if(!(parameterTypes==null&¶meterTypes.length==0)){for(int i=0;iif(i==parameterTypes.length-1){System.out.print(parameterTypes[i].getName()+"args_"+i);break;}System.out.print(parameterTypes[i].getName()+"args_"+i+",");}}System.out.print(")");System.out.println();//6.抛出的异常Class[] exceptionTypes = m.getExceptionTypes();if(!(exceptionTypes==null&&exceptionTypes.length==0)){System.out.print("throws");for(int i=0;iif(i==exceptionTypes.length-1){System.out.print(exceptionTypes[i].getName());break;}System.out.print(exceptionTypes[i].getName()+",");}}System.out.println();}}
}
(3)获取构造器结构:
@Testpublic void test(){Class clazz=Person.class;//getConstructors():获取当前运行时类中声明为public的构造器Constructor[] constructors = clazz.getConstructors();for(Constructor c:constructors){System.out.println(c);}System.out.println();//获取当前运行时类中声明的所有的构造器Constructor[] declaredConstructors = clazz.getDeclaredConstructors();for(Constructor c:declaredConstructors){System.out.println(c);}}
5.调用运行时类中指定的结构
(1)如何操作运行时类中的指定的属性:
@Testpublic void testField1() throws Exception {Class clazz=Person.class;//创建运行时类的对象Person p=(Person)clazz.newInstance();//1.getDeclaredField(String name):获取运行时类中指定变量名的属性Field name= clazz.getDeclaredField("name");//2.保证当前属性是可访问的name.setAccessible(true);//3.获取、设置指定对象的属性值name.set(p,"tom");System.out.println(name.get(p));}
(2)如何操作运行时类中的指定的方法:
@Testpublic void testMeThod() throws Exception {Class clazz=Person.class;//创建运行时类的对象Person p=(Person)clazz.newInstance();//1.获取指定的某个方法//getDeclaredMethod():参数1:指明获取的方法的名称 参数2:指明获取的方法的形参列表Method show = clazz.getDeclaredMethod("show", String.class);//2.保证当前方法是可访问的show.setAccessible(true);//3.invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参//invoke()的返回值即为对应类中调用的方法的返回值Object chn = show.invoke(p, "CHN");System.out.println(chn);}