当前位置:首页 > 开发 > 编程语言 > Java > 正文

java反射类与方法

发表于: 2015-03-09   作者:ciaos   来源:转载   浏览:
摘要: 测试代码:java package com.demo; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Demo { public static void main(String[] args) { // TODO Aut

测试代码:java

package com.demo;

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

public class Demo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String service="ApiOne.hello";
	
		String[] tmpstr = service.split("\\.",2);
		
		Class<?> classname = null;
		try {
			try {
				classname = Class.forName("com.api."+tmpstr[0]).newInstance().getClass();
			} catch (InstantiationException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		
		Method method = null;
		try {
			method = classname.getDeclaredMethod(tmpstr[1], String.class);
		} catch (NoSuchMethodException | SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		
		
		try {
			try {
				method.invoke(classname.newInstance(), "I am caller");
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

类:

package com.api;

public class ApiOne {
	public void hello(String params){
		System.out.println("ApiOne " + params);
	}
}

 

package com.api;

public class ApiTwo {
	public void bye(String params){
		System.out.println("ApiTwo " + params);
	}
}

 

 

java反射类与方法

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号