欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java反射初探

程序员文章站 2023-12-30 08:02:46
...
package com.javareflect.base.demo;

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

public class InvokerTester {

public int add(int m, int n) {
return m + n;
}

public String echo(String message) {
return "hello" + message;
}

private String sayHello(String str) {
return "hello"+str;
}

public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<?> classType = InvokerTester.class;//获取类对象
Object invokerTester = classType.newInstance();//获取类的实例
Method addMethod = classType.getMethod("add", new Class[] { int.class, int.class });
Object result = addMethod.invoke(invokerTester, new Object[] { 1, 2 });
System.out.println(result);
Method echoMe = classType.getMethod("echo", new Class[]{String.class});
Object r2 = echoMe.invoke(invokerTester, new Object[]{"ffffffffff"});
System.out.println(r2);

Method sayMe = classType.getDeclaredMethod("sayHello", new Class[]{String.class});
sayMe.setAccessible(true);
String s = (String)sayMe.invoke(invokerTester, new Object[]{"ggggggg"});
System.out.println(s);
}

}
[size=large][size=medium]
[/size][/size]
相关标签: java

上一篇:

下一篇: