Java反射之——方法反射的基本操作

package com.imooc.reflect;

import java.lang.reflect.Method;

public class MethodDemo1 {
	public static void main(String[] args) throws Exception {
		//要获取print(int ,int )方法 
		//1,要获取一个方法就是获取类的信息,获取类的信息首先要获取类的类类型
		A a = new A();
		Class class1 = a.getClass();
		/*2,获取方法名称和参数列表
		 * getMethod获取的是public的方法
		 * getDelcaredMethod自己声明的方法
		 */
			Method method = class1.getMethod("print", new Class[]{int.class,int.class} );
//			Method method2 = class1.getMethod("print", int.class,int.class);//也可以
			
			//方法的反射操作
		//	a.print(10, 20);//
			//方法的反射操作是用method对象来进行方法调用和al.print调用的效果一致
			//方法如果没有返回值null,有返回值返回具体的返回值
		//	method.invoke(a, new Object[]{10,20});//invoke:調用
			Object object = method.invoke(a, 10,20);//有几个参数就写几个,也可以的喔
			
			//
			System.out.println("===========================");
			//获取方法print(String,String)
			Method method2 = class1.getMethod("print", String.class,String.class);
			//用方法进行反射操作
//			a.print("hello", "world");
			object = method2.invoke(a, "HELLO","WORLD");
			
			//
			System.out.println("===========================");
//			Method method3 = class1.getMethod("print", new Class[]{});
			Method method3 = class1.getMethod("print");
//			method3.invoke(a, new Object[]{});
			method3.invoke(a);//沒有参数列表就不写,这个invoke方法本来就是可变参数的。。。
	}
}
class A{
	public void print(){
		System.out.println("无参数的print方法");
	}
	public void print(int a,int b){
		System.out.println(a+b);
	}
	public void print(String a,String b){
		System.out.println(a.toUpperCase()+","+b.toLowerCase());
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

绝地反击T

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

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

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

打赏作者

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

抵扣说明:

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

余额充值