java反射机制(笔记)
java反射机制就是获取出class的相应方法
例如 获取构造函数:
模版:
Class test = Class.forName("cn.test.Person");//得到相应的class Constructor test1 = test.getConstructor(null); //获取空的够着函数 Person person = (Person) test1.newInstance(null);//new一个新对象
//这里是访问私有的构造函数,进行暴力反射 Constructor c3 = test3.getDeclaredConstructor(List.class);//获得私有的构造 c3.setAccessible(true);//暴力反射
反射函数模版:
//实例化一个对象
Class classtest = Class.forName(""); Method method = classtest.getMethod("方法名",参数);//参数多个用逗号隔开 method.invoke(对象,参数);//首先要创建一个实例化类,然后再进行调用
反射main方法
Class testmain = Class.forName("cn.test.Person");//得到对象 Method tt = testmain.getMethod("main",String[].class);//得到main方法 tt.invoke(null, new Object[]{new String[]{"aa","bbb"}});//调用
得到字段:
Person person = new Person("yy"); Class cla = Class.forName("cn.test.Person"); Field field = cla.getField("name");//得到name String name = (String) field.get(person); System.out.println(name);
例子:
//Person类 package cn.test; import static java.lang.System.out; import java.awt.List; public class Person { private String name; public Person(){ out.print("nulllllllll"); } public Person(String name){ out.println(name); this.name = name; } public Person(String name,int n){ out.print(""+name+" "+n); } private Person(List l){ out.print("static person"); } public void getint(int x){ System.out.println("x=="+x); } public static void main(String[] args){ System.out.print("main "); } }
//测试类 package cn.test.test; import java.awt.List; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.junit.Test; import cn.test.Person; public class test { @Test public void test1() throws Exception{ Class test = Class.forName("cn.test.Person"); Constructor test1 = test.getConstructor(null); Person person = (Person) test1.newInstance(null); } @Test public void test2() throws Exception{ Class test2 = Class.forName("cn.test.Person"); Constructor c2 = test2.getConstructor(String.class); Person person = (Person) c2.newInstance("xxvdfdfd"); } @Test public void test3() throws Exception{ Class test3 = Class.forName("cn.test.Person"); Constructor c3 = test3.getDeclaredConstructor(List.class); c3.setAccessible(true); Person person = (Person) c3.newInstance(new List()); } //反射得到方法 @Test public void test4() throws Exception{ Person person = new Person(); Class test4 = Class.forName("cn.test.Person"); Method tt = test4.getMethod("getint", int.class); tt.invoke(person, 12); } //反射得到买你函数 @Test public void testmain() throws Exception{ Class testmain = Class.forName("cn.test.Person"); Method tt = testmain.getMethod("main",String[].class); tt.invoke(null, new Object[]{new String[]{"aa","bbb"}}); } //反射得到字段 @Test public void getname() throws Exception{ Person person = new Person("yy"); Class cla = Class.forName("cn.test.Person"); Field field = cla.getField("name");//得到name String name = (String) field.get(person); System.out.println(name); } }
yy_room