java通过反射获取并调用对象方法探究

package test;
/**
 * 测试类
 */
public class TestService {
	
	public String testMethod(){
		return "success test method";
	}

	private String testMethod(String param){
		return "success test method param = " +param;
	}

	public String testMethod(String param1,String param2){
		return "success test method param1 = " +param1 + " param2="+param2;
	}
	
	public String testMethod(String param1,int param2){
		return "success test method param1 = " +param1 + " param2="+param2;
	}

}
package test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Test;

public class TestController {
	@Test
	public void testField() {
	    try {
	    	//根据类名获取所需类
			Class<?> clazz = Class.forName("test.TestService");
			//实例化对象
			Object a = clazz.newInstance();
			//获取对象中的所有方法,包括私有方法
	    	Method[] methods = clazz.getDeclaredMethods();
		    for (Method method : methods) {
		    	//获取方法所需参数个数以及类型
		        Object[] objs = null;
		        if (method.getParameterTypes().length>0) {
		        	objs = new Object[method.getParameterTypes().length];
		        	int index = 0;
		        	for (Object parameterType : method.getParameterTypes()) {
		        		if (parameterType==String.class) {
		        			objs[index++] = "a";
						}else if (parameterType==Integer.class||parameterType==int.class) {
						//可扩展为是否是数字类型
		        			objs[index++] = 1;
						}
					}
				}
				//这里需要注意。检查方法是否为private,如果是需要设置方法的accessible
				//否则会发生异常 java.lang.IllegalAccessException: Class test.TestController can not access a member of class test.TestService with modifiers "private"
				//accessible 值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false 则指示反射的对象应该实施 Java 语言访问检查。
		        if (Modifier.isPrivate(method.getModifiers())) {
					method.setAccessible(true);
				}
				//携带请求参数,否则会发生异常 java.lang.IllegalArgumentException: wrong number of arguments
		        Object o = method.invoke(a,objs);
		        System.out.println(o);
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

#输出结果
success test method param1 = a param2=1
success test method param1 = a param2=a
success test method param = a
success test method

以上是反射对象中不存在注入的情况下可以使用的方法,一旦涉及到注入的时候,直接使用clazz.newInstance()会导致原本对象中注入的内容变为空值,这里需要通过spring去获取对象bean。

package test;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class TestController {
	
	@Test
	public void testField() {
	    try {
			//初始化spring
	    	ApplicationContext ac = new ClassPathXmlApplicationContext(new String[] { "spring-test.xml" });
			Class<?> clazz = Class.forName("test.TestService");
			//获取bean而不是直接创建实例
			Object a = ac.getBean(clazz);
//			Object a = clazz.newInstance();
	    	Method[] methods = clazz.getDeclaredMethods();
		    for (Method method : methods) {
		        Object[] objs = null;
		        if (method.getParameterTypes().length>0) {
		        	objs = new Object[method.getParameterTypes().length];
		        	int index = 0;
		        	for (Object parameterType : method.getParameterTypes()) {
		        		if (parameterType==String.class) {
		        			objs[index++] = "a";
						}else if (parameterType==Integer.class||parameterType==int.class) {//可扩展为是否是数字类型
		        			objs[index++] = 1;
						}
					}
				}
		        if (Modifier.isPrivate(method.getModifiers())) {
					method.setAccessible(true);
				}
		        Object o = method.invoke(a,objs);
		        System.out.println(o);
		    }
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
<!-- 对应的spring-test.xml文件 -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	<!-- 配置要扫描的包 -->
	<context:component-scan base-package="test"></context:component-scan>
</beans>
#输出结果
success test method param1 = a param2=1
success test method param1 = a param2=a
success test method param = a
test auto wired
success test method
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值