【通過反射獲取無參構造方法並使用】


package test;

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

/**
 * @author shusheng
 * @description 通過反射獲取無參構造方法並使用
 * @Email shusheng@yiji.com
 * @date 2018/12/23 23:49
 */
public class ReflectDemo1 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 獲取字節碼文件對象
        Class c = Class.forName("test.Person");

        // 獲取構造方法
        // public Constructor[] getConstructors():所有公共構造方法
        // public Constructor[] getDeclaredConstructors():所有構造方法
        Constructor[] cons = c.getDeclaredConstructors();
        for (Constructor con : cons) {
            System.out.println(con);
        }

        // 獲取單個構造方法
        // public Constructor<T> getConstructor(Class<?>... parameterTypes)
        // 參數表示的是:你要獲取的構造方法的構造參數個數及數據類型的class字節碼文件對象
        Constructor con = c.getConstructor();

        // Person p = new Person();
        // System.out.println(p);
        // public T newInstance(Object... initargs)
        // 使用此 Constructor 對象表示的構造方法來創建該構造方法的聲明類的新實例,並用指定的初始化參數初始化該實例。
        Object obj = con.newInstance();
        System.out.println(obj);

         Person p = (Person)obj;
         p.show();
    }

}
package test;

/**
 * @author shusheng
 * @description
 * @Email shusheng@yiji.com
 * @date 2018/12/23 23:49
 */
public class Person {
    private String name;
    int age;
    public String address;

    public Person() {
    }

    private Person(String name) {
        this.name = name;
    }

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public void show() {
        System.out.println("show");
    }

    public void method(String s) {
        System.out.println("method " + s);
    }

    public String getString(String s, int i) {
        return s + "---" + i;
    }

    private void function() {
        System.out.println("function");
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", address="
                + address
                + "]";
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM