java编程 反射类的使用

来源:互联网 发布:美图秀秀软件介绍 编辑:程序博客网 时间:2024/04/28 12:32

使用反射类调用该类方法:

package com.robert.reflect;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class InvokerTest {public int add(int a, int b){return a + b;}public String echo(String str){return "echo " + str;}public static void main(String[] args){Class classType = InvokerTest.class;try {//Object invokerTest = classType.newInstance();Object invokerTest = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});Method addMethod = classType.getMethod("add", new Class[]{int.class,int.class});Object result = addMethod.invoke(invokerTest, new Object[]{100,200});System.out.println(result.toString());Method echoMethod = classType.getMethod("echo", new Class[]{String.class});Object echoResult = echoMethod.invoke(invokerTest, new Object[]{"hello world"});System.out.println(echoResult.toString());} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (SecurityException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}}

注明:该代码转自浪曦视频。仅供学习和参考。如有问题,本人qq362601125


原创粉丝点击