非深入探寻Java反射机制 (Methods)

来源:互联网 发布:化学查询软件下载 编辑:程序博客网 时间:2024/05/24 16:14

通过 java.lang.reflect.Method,我们可以在运行时访问并调用类的方法。



  • Obtaining Method Objects


如果知道方法的签名,则可以直接取出指定的方法:

package tao.xiao.action;import java.lang.reflect.Method;public class A implements IT1 {public void f1() {}public void f1(String s) { }public String f2(int x) { return "xxx"; };public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException {Class myClass = Class.forName("tao.xiao.action.A");Method[] methods = myClass.getMethods();//取得全部的方法Method m1 = myClass.getMethod("f1", null);//函数没有参数则传入nullMethod m2 = myClass.getMethod("f1", new Class[]{String.class});Method m3 = myClass.getMethod("f2", new Class[]{int.class});System.out.println(m1);System.out.println(m2);System.out.println(m3);}}

运行结果为

public void tao.xiao.action.A.f1()public void tao.xiao.action.A.f1(java.lang.String)public java.lang.String tao.xiao.action.A.f2(int)




  • Method Parameters and Return Types


package tao.xiao.action;import java.lang.reflect.Method;public class A implements IT1 {public String[] f(int x, double[] y, String z) { return null; };public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException {Class myClass = Class.forName("tao.xiao.action.A");Method m = myClass.getMethod("f", new Class[]{int.class, double[].class, String.class});Class[] parameterTypes = m.getParameterTypes();for (Class parameterType : parameterTypes)System.out.println(parameterType);Class returnType = m.getReturnType();System.out.println(returnType);}}

运行结果为:

intclass [Dclass java.lang.Stringclass [Ljava.lang.String;



  • Invoking Methods using Method Object


package tao.xiao.action;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class A implements IT1 {public String[] f1(int x, double[] y, String z) { System.out.println("f1: x = " + x + ", y = " + y + ", z = " + z);return new String[]{"AAA", "BBB"};}public static void f2(int x) { System.out.println("f2: x = " + x); }public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException {Method m1 = A.class.getMethod("f1", new Class[]{int.class, double[].class, String.class});Method m2 = A.class.getMethod("f2", int.class);A objA = new A();String[] ss = (String[])m1.invoke(objA, 100, new double[]{200, 300, 400}, "haha");for (String s : ss)System.out.println(s);m2.invoke(null, 330);// 对于static方法,invoke的第一个参数传入null}}
运行结果为

f1: x = 100, y = [D@61de33, z = hahaAAABBBf2: x = 330




下一章:非深入探寻Java反射机制(Getters and Setters)

原创粉丝点击