Java中反射getDeclaredMethods和getMethods区别

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/suo082407128/article/details/89968753

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

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

猜你喜欢

转载自blog.csdn.net/suo082407128/article/details/89968753