跳转到内容

动态调用

50% developed
来自维基教科书,开放的书籍,开放的世界

导航 反射 主题: v  d  e )

我们从基本的传输对象开始

Computer code 代码清单 10.1: DummyTo.java
package com.test;
 
public class DummyTo {
    private String name;
    private String address;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
    public DummyTo(String name, String address) {
        this.name = name;
        this.address = address;
    }
 
    public DummyTo() {
        this.name = new String();
        this.address = new String();
    }
 
    public String toString(String appendBefore) {
        return appendBefore + " " + name + ", " + address;
    }
}

以下是使用反射动态调用上述方法的示例。代码是自解释的。

Computer code 代码清单 10.2: ReflectTest.java
package com.test;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
public class ReflectTest {
    public static void main(String[] args) {
        try {
            Class<?> dummyClass = Class.forName("com.test.DummyTo");
 
            // parameter types for methods
            Class<?>[] partypes = new Class[]{String.class};
 
            // Create method object. methodname and parameter types
            Method meth = dummyClass.getMethod("toString", partypes);
 
            // parameter types for constructor
            Class<?>[] constrpartypes = new Class[]{String.class, String.class};
 
            //Create constructor object. parameter types
            Constructor<?> constr = dummyClass.getConstructor(constrpartypes);
 
            // create instance
            Object dummyto = constr.newInstance(new Object[]{"Java Programmer", "India"});
 
            // Arguments to be passed into method
            Object[] arglist = new Object[]{"I am"};
 
            // invoke method!!
            String output = (String) meth.invoke(dummyto, arglist);
            System.out.println(output);
 
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
Standard input or output 代码清单 10.2 的控制台
I am Java Programmer, India

结论: 上述示例演示了使用反射动态调用方法。


Clipboard

待办事项
添加一些类似于 变量 中的练习

华夏公益教科书