反射操作構造方法

1.1.1 通過獲取的構造創建對象
步驟:
1.獲得Class對象
2獲得構造
3.通過構造對象獲得實例化對象

package com.itheima_01;

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

/*

 *        通過反射獲取構造方法並使用

 *        Constructor<?>[] getConstructors() 

 *        Constructor<T> getConstructor(Class<?>... parameterTypes)

 *         T newInstance()  

 *

 *Constructor:

 *                 T newInstance(Object... initargs) 

 */

public class ReflectDemo2 {

public static void main(String[] args) throws ReflectiveOperationException {

Class clazz = Class.forName("com.itheima_01.Student");

//method(clazz);

//Constructor<T> getConstructor(Class<?>... parameterTypes)

//method2(clazz);

//method3(clazz);

Object obj = clazz.newInstance();

System.out.println(obj);

}

private static void method3(Class clazz)

throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {

Constructor c = clazz.getConstructor(String.class,int.class);//獲取有參構造,參數1類型爲String,參數2類型爲int

System.out.println(c);

Object obj = c.newInstance("lisi",30);

System.out.println(obj);

}

private static void method2(Class clazz)

throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {

Constructor c = clazz.getConstructor();//獲取無參構造

System.out.println(c);

Object obj = c.newInstance();

System.out.println(obj);

}

private static void method(Class clazz) {

//Constructor<?>[] getConstructors() :獲取所有public修飾的構造方法

Constructor[] cs = clazz.getConstructors();

for (int i = 0; i < cs.length; i++) {

System.out.println(cs);

}

}

}

1.1.2 問題: 直接通過Class類中的newInstance()和獲取getConstructor()有什麼區別?
newInstance()方法, 只能通過空參的構造方法創建對象
getConstructor(Class<T>… parameterTypes)方法, 方法接受一個可變參數, 可以根據傳入的類型來匹配對應的構造方法

總結
Constructor<?>[] getConstructors()
Constructor<T> getConstructor(Class<?>... parameterTypes)

                    方法1: 獲取該類中所有的構造方法, 返回的是一個數組
                    方法2: 方法接受一個可變參數, 可以根據傳入的類型, 來匹配對應的構造方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章