1 Star 0 Fork 0

cxylk / Java-Notes

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
反射.md 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
likuisuper 提交于 2020-10-27 18:53 . :art:添加Java基础文件

获取方法

getDeclaredMethod和getMethod的区别

  • getDeclaredMethod可获取任意方法,像protected修饰的,但是当获取private修饰的方法时,要设置成可访问的,不然会抛出java.lang.IllegalAccessException异常
private void testPrivate(){
	System.out.println("private..");
}

//5.调用私有的方法 - 反射可以破坏封装性
Method m5=c.getDeclaredMethod("testPrivate");
m5.setAccessible(true);
m5.invoke(p);
  • getMethod只可获取public修饰符修饰的方法,不然会抛出java.lang.NoSuchMethodException异常
private(或者protected) void test(){
	System.out.println("test()...");
}
抛出异常

反射调用构造方法

  • getDeclaredConstructors()获取所有方法,包括private和protected
  • getConstructors()只能获取public方法,不是Public的访问不到
public Point(int x, String y) {
	System.out.println("x:"+x+",y:"+y);
}

private Point(int x, String y) {
	System.out.println("x:"+x+",y:"+y);
}
//1.调用空参构造有两种方式
//a.直接通过java.lang.Class<T>中提供的newInstance()
	try {
        Point p= (Point) c.newInstance();

        //b.通过java.lang.reflect.Constructor提供的newInstance
        Constructor<?> c1=c.getDeclaredConstructor();
        Point p2= (Point) c1.newInstance();

        //2.调用带参构造只有一种
        Constructor<?> c2=c.getDeclaredConstructor(int.class,String.class);
        //c2.setAccessible(true);//如果该构造方法是private的
        Point p3= (Point) c2.newInstance(200,"java");
   }
1
https://gitee.com/cxylk/Java-Notes.git
git@gitee.com:cxylk/Java-Notes.git
cxylk
Java-Notes
Java-Notes
main

搜索帮助

53164aa7 5694891 3bd8fe86 5694891