欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java通过反射调用方法的两个例子,java反射调用例子,java通过反射调用方法

来源: javaer 分享于  点击 3290 次 点评:269

java通过反射调用方法的两个例子,java反射调用例子,java通过反射调用方法


java通过反射调用方法的两个例子:

例子一: 调用无参数方法:

import java.lang.reflect.*;import java.io.*;public class TestReflect {   public static void main(String s[]) throws Exception{      String aClass;      String aMethod;      // we assume that called methods have no argument      Class params[] = {};      Object paramsObj[] = {};      while (true) {         aClass  = lineInput("\nClass : ");         aMethod = lineInput("Method: ");         // get the Class         Class thisClass = Class.forName(aClass);         // get an instance         Object iClass = thisClass.newInstance();         // get the method         Method thisMethod = thisClass.getDeclaredMethod(aMethod, params);         // call the method         System.out.println            (thisMethod.invoke(iClass, paramsObj).toString());      }      /* Output examples:            Class : Class1            Method: class1Method2            ### Class 1, Method2 ###            Class : java.util.Date            Method: toString            Sat Aug 11 13:18:39 EDT 2007            Class : java.util.Date            Method: getTime            1186852732140             */   }   public static  String lineInput (String prompt) throws IOException {     BufferedReader input =        new BufferedReader(new InputStreamReader(System.in));     System.out.print(prompt);     return input.readLine();   }}class Class1 {   public String class1Method1() {      return "*** Class 1, Method1 ***";   }   public String class1Method2() {      return "### Class 1, Method2 ###";   }}

例子二:调用有参数方法

import java.lang.reflect.*;public class TestReflect {  public static void main(String[] args) throws Exception {    TestReflect.invoke("Class1", "say", new Class[] {String.class, String.class},           new Object[]             {new String("Hello"), new String("World")});    /*      output :         Hello World    */  }  public static void invoke     (String aClass, String aMethod, Class[] params, Object[] args)     throws Exception {    Class c = Class.forName(aClass);    Method m = c.getDeclaredMethod(aMethod, params);    Object i = c.newInstance();    Object r = m.invoke(i, args);  }}class Class1 {  public void say( String s1, String s2) {    System.out.println(s1 + " " + s2);  }}
相关栏目:

用户点评