package cclass;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class He {
public String show() {
return "是个人";
}
public String show(String name) {
return name + "是个人";
}
public String friend(String name, String meFriend) {
return meFriend + "是" + name + "的朋友";
}
public String friend(String name, String meFriend, String[] friend) {
StringBuffer string = new StringBuffer(meFriend + "是" + name + "的朋友" + name + "还有一些朋友比如:");
for (String str : friend) {
string.append(str + "\t");
}
return string.toString();
}
}
public class cclass {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<He> he = He.class;
He hh = he.newInstance();
Method[] mods = he.getMethods();
System.out.println("一下打印He类的所有方法");
for (Method mod : mods) {
System.out.println(mod);
}
// 写法一
/*
* 我建议使用第一种写法原因如一下注释内容:
*
* 有人说:数组类型的参数必须包含在new Object[]{}中,否则会报IllegalArgumentException
* 来自:http://blog.youkuaiyun.com/u013473691/article/details/52633800
* Method的invoke()方法的使用
*
* 在我写的过程中还没报过错
*/
Method show = he.getMethod("show", String.class);
String str = (String) show.invoke(hh, "aksjxajk");
System.out.println(str);
Method friend = he.getMethod("friend", String.class, String.class);
str = (String) friend.invoke(hh, "aksjxajk", "dcsdcs");
System.out.println(str);
Method friends = he.getMethod("friend", String.class, String.class, String[].class);
str = (String) friends.invoke(hh, "aksjxajk", "dcsdcs", new String[] { "asxasxa", "asxasx", "asxasx" });
System.out.println(str);
// 写法二
/*
* 看到有人说Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,
* 如果参数为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,
* 如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象, 再将其返回 来自:
* http://blog.youkuaiyun.com/kevinwu629/article/details/5801385 一个例子弄懂invoke方法
*
* 目前还不知道有什么好处,写的太累不值得
*
* 我的传参:str3 = (String) friends3.invoke(hh, new Object[] { "aksjxajk", "dcsdcs",
* new String[] { "asxasxa", "asxasx", "asxasx" } });
* 他建议的传参方式:str3 = (String)
* friends3.invoke(hh, new Object[] { new String("aksjxajk"), new
* String("dcsdcs"), new String[] { "asxasxa", "asxasx", "asxasx" } });
*/
Method show3 = he.getMethod("show", new Class[] { String.class });
String str3 = (String) show3.invoke(hh, new Object[] { "aksjxajk" });
System.out.println(str3);
Method friend3 = he.getMethod("friend", new Class[] { String.class, String.class });
str3 = (String) friend3.invoke(hh, new Object[] { "aksjxajk", "dcsdcs" });
System.out.println(str3);
Method friends3 = he.getMethod("friend", new Class[] { String.class, String.class, String[].class });
str3 = (String) friends3.invoke(hh,
new Object[] { "aksjxajk", "dcsdcs", new String[] { "asxasxa", "asxasx", "asxasx" } });
System.out.println(str3);
}
}
getMethods、getMethod和invoke()方法的使用
最新推荐文章于 2022-07-09 16:28:50 发布