Java中反射getDeclaredMethods和getMethods区别

1.getMethods是获取类中所有公共方法,包括继承自父类的

2.getDeclaredMethods是获取类中自己声明的方法,即自己声明的任何权限的方法,包括私有方法

getDeclaredFields、getFields同理,所有Declared都是这个意思

获取到一个类的实体后,你可以获取到该类中所有的方法,甚至父类中所有方法(包括私有)

getClass().getSuperClass(),并通过设置setAccessible(true),即可对方法或字段进行操作

示例:

public class MethodTest {
	public static class Shape{
		private String a;
		private void getPrivate() {
			System.out.println("private");
		}
		void getDefault(){
			System.out.println("default");
		}
		protected void getProtected() {
			System.out.println("protected");
		}
		public void getPublic() {
			System.out.println("public");
		}
		@Override
		public String toString() {
			return a;
		}
	}
	
	public static class Circle extends Shape{
		
	}
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
		Shape shape = new Shape();
		System.out.println("父类getMethods");
		for(Method m : shape.getClass().getMethods()) {
			System.out.println(m.getName());
		}
		System.out.println("-------------------\n父类getDeclaredMethods");
		for(Method m : shape.getClass().getDeclaredMethods()) {
			System.out.println(m.getName());
		}
		System.out.println("---------华丽的分割线------------\n子类getMethods");
		shape = new Circle();
		for(Method m : shape.getClass().getMethods()) {
			System.out.println(m.getName());
		}
		System.out.println("-------------------\n子类getDeclaredMethods");
		for(Method m : shape.getClass().getDeclaredMethods()) {
			System.out.println(m.getName());
		}
		System.out.println("-------------------\n设置父类私有字段");
		Shape s=new Shape();
		Field f=shape.getClass().getSuperclass().getDeclaredField("a");
		f.setAccessible(true);
		f.set(s, "sdf");
		System.out.println(s);
	}
}

运行结果:

父类getMethods
toString
getPublic
wait
wait
wait
equals
hashCode
getClass
notify
notifyAll
-------------------
父类getDeclaredMethods
toString
getDefault
getPrivate
getPublic
getProtected
---------华丽的分割线------------
子类getMethods
toString
getPublic
wait
wait
wait
equals
hashCode
getClass
notify
notifyAll
-------------------
子类getDeclaredMethods
-------------------
设置父类私有字段
sdf

希望大家还是自己动手码一下,看懂是一回事,码是另一回事

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

椰汁菠萝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值