代码如下
public class test {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class c = Class.forName("com.demo.pojo.user");
Object obj = c.newInstance();
Method[] methods = c.getMethods();
for (Method method:
methods) {
System.out.println(method);
}
Method method = c.getMethod("getName", String.class);
System.out.println(method.invoke(c, obj));
}
}
输出结果如下
public java.lang.String com.demo.pojo.user.getName()
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
Exception in thread "main" java.lang.NoSuchMethodException: com.demo.pojo.user.getName(java.lang.String)
at java.base/java.lang.Class.getMethod(Class.java:2108)
at com.demo.reflection.test.main(test.java:15)
可以看到找到了com.demo.pojo.user.getName()这个方法,但是执行c.getMethod("getName", String.class)却提示异常,说没有该方法???
以下是类user的代码
package com.demo.pojo;
public class user {
public String getName(){
return "User";
}
}
public class test {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class c = Class.forName("com.demo.pojo.user");
Object obj = c.newInstance();
Method[] methods = c.getMethods();
for (Method method:
methods) {
System.out.println(method);
}
//getName方法没有参数哦,可变参数列表不传
Method method = c.getMethod("getName");
//此处同上
System.out.println(method.invoke(obj));
}
}
ps:java规范,类名大写哦
昨天复习反射,确实没注意明明规范,谢谢提醒啦。
com.demo.pojo.user.getName(java.lang.String)
这里的 String.class 是指 参数哦
哈哈,没看仔细,丢脸了(/▽\)。
谢谢啦