Java反射——方法的反射

方法的反射

1
package com.imooc.reflect;
2
3
import java.lang.reflect.Method;
4
5
public class MethodDemo1 {
6
	public static void main(String[] args) {
7
	   //要获取print(int ,int )方法  1.要获取一个方法就是获取类的信息,获取类的信息首先要获取类的类类型
8
		A a1 = new A();
9
		Class c = a1.getClass();
10
		/*
11
		 * 2.获取方法 名称和参数列表来决定  
12
		 * getMethod获取的是public的方法
13
		 * getDelcaredMethod自己声明的方法
14
		 */
15
	    try {
16
			//Method m =  c.getMethod("print", new Class[]{int.class,int.class});
17
	    	Method m = c.getMethod("print", int.class,int.class);
18
19
	    	//方法的反射操作  
20
	    	//a1.print(10, 20);方法的反射操作是用m对象来进行方法调用 和a1.print调用的效果完全相同
21
	        //方法如果没有返回值返回null,有返回值返回具体的返回值
22
	    	//Object o = m.invoke(a1,new Object[]{10,20});
23
	    	Object o = m.invoke(a1, 10,20);
24
	    	System.out.println("==================");
25
	    	//获取方法print(String,String)
26
             Method m1 = c.getMethod("print",String.class,String.class);
27
             //用方法进行反射操作
28
             //a1.print("hello", "WORLD");
29
             o = m1.invoke(a1, "hello","WORLD");
30
             System.out.println("===================");
31
           //  Method m2 = c.getMethod("print", new Class[]{});
32
                Method m2 = c.getMethod("print");
33
               // m2.invoke(a1, new Object[]{});
34
                m2.invoke(a1);
35
		} catch (Exception e) {
36
			// TODO Auto-generated catch block
37
			e.printStackTrace();
38
		}
39
40
	}
41
}
42
class A{
43
	public void print(){
44
		System.out.println("helloworld");
45
	}
46
	public void print(int a,int b){
47
		System.out.println(a+b);
48
	}
49
	public void print(String a,String b){
50
		System.out.println(a.toUpperCase()+","+b.toLowerCase());
51
	}
52
}

参考资料

https://www.imooc.com/learn/199

  • © 2020 QSH
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信