Java反射(二)

package reflectiondemo;

public class TwoString {

    private String m_s1="a", m_s2="b";

//    无参数构造函数
    public  TwoString(){

    }

//    含参数构造函数
    public TwoString(String s1, String s2){
        this.m_s1 = s1;
        this.m_s2 = s2;
    }

    public void setM_s1(String s1){
        this.m_s1 = s1;
    }

    public void setM_s2(String s2){
        this.m_s2 = s2;
    }

    public String getM_s1(){
        return this.m_s1;
    }

    public String getM_s2(){
        return this.m_s2;
    }
}

反射调用一:调用无参构造函数

package reflectiondemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class test {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

//        利用反射机制创建对象:无参构造函数
        Constructor cons = TwoString.class.getConstructor();
        TwoString ts = (TwoString) cons.newInstance();

//        利用反射机制操作方法
        Class aclass = Class.forName("reflectiondemo.TwoString");
        Method method = aclass.getMethod("setM_s1", String.class);
        method.invoke(ts, "abcdefghijklmn");
        System.out.println(ts.getM_s1());

    }
}

反射调用二:调用含参构造函数

package reflectiondemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class test {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

//        利用反射机制创建对象:含参构造函数
        Class[] types = new Class[] {String.class, String.class};
        Class aclass = Class.forName("reflectiondemo.TwoString");
        Constructor cons = aclass.getConstructor(types);
        String[] args1 = new String[] {"a", "b"};
        TwoString ts = (TwoString) cons.newInstance(args1);

//        利用反射机制操作方法
        aclass = Class.forName("reflectiondemo.TwoString");
        Method method = aclass.getMethod("setM_s1", String.class);
        method.invoke(ts, "abcdefghijklmn");
        System.out.println(ts.getM_s1());
    }
}

你可能感兴趣的:(Java反射(二))