利用反射实现同时返回两个或者多个参数

利用反射实现同时返回两个或者多个参数

主类
package com.aaa.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvokeMethod1 {

	/**
	 * 通过反射,调用类中的方法
	 * 
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws InstantiationException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static void main(String[] args) throws Exception {
		try {
			//对com.aaa.test.Student进行反射加载
			Class student = Class.forName("com.aaa.test.Student");// 动态加载类,获取当前类的Class对象
			// 获取Student类名称为printinfo地方法
			Method methods1 = student.getMethod("print");
			// 通过实例化的对象,调用无参数的方法
			methods1.invoke(student.newInstance()); 
			// 获取类中名称为printInfo地方法,String,class是参数类型
			Method methods2 = student.getMethod("print", String.class);// 注意参数不是String
			// 调用printAddress方法,其中HN是方法传入的参数值
			methods2.invoke(student.newInstance(), "HN");// 通过对象,调用有参数的方法
			
			
			//初始化a,b两者的值
			int a = 1; int b =1;
			//反射出student中的calculate方法,参数类型是int,int
			Method methods3 = student.getMethod("calculate",int.class,int.class);
			//调用反射方法,有返回值,并且在参数值已经改变
			boolean bl = (boolean)methods3.invoke(student.newInstance(), a,b);
			System.out.println(a+"===="+b+"====="+bl);
			
			//反射出student中的sum方法,参数类型是int,int
			Method methods4 = student.getMethod("sum",int.class,int.class);
			//调用反射方法,有返回值
			Object o =methods4.invoke(student.newInstance(), a,b);
			System.out.println(o+"==="+o.getClass());
			
			//反射出student中的私有函数count方法,参数类型是int,int
			Method methods5 = student.getDeclaredMethod("count",int.class,int.class);
			methods5.setAccessible(true);
			//调用反射方法,有返回值
			Object o2 =methods5.invoke(student.newInstance(), a,b);
			System.out.println(o2+"==="+o2.getClass());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
被反射的类
package com.aaa.test;
 
import java.lang.reflect.InvocationTargetException;
 
public class Student {
	public void print(){
	    System.out.println("打印学生信息");
	}
	public void print(String address){
	    System.out.println("hello,"+address);
	     
	}
	public boolean calculate(int a,int b){
		a = a+1;
		b = b-1;
		return true;
	}
	public int sum(int a,int b){
		return a+b;
	}
	private int count(int a,int b){
		return a+b;
	}
}
结果
打印学生信息
hello,HN
1====1=====true
2===class java.lang.Integer
2===class java.lang.Integer

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值