反射_Class对象功能_获取Constructor
生活随笔
收集整理的這篇文章主要介紹了
反射_Class对象功能_获取Constructor
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
* Constructor:構(gòu)造方法
?? ?* 創(chuàng)建對象:
?? ??? ?* T newInstance(Object... initargs) ?
?? ??? ?* 如果使用空參數(shù)構(gòu)造方法創(chuàng)建對象,操作可以簡化:Class對象的newInstance方法
package cn.learn.reflect;import cn.learn.domain.Person;import java.lang.reflect.Constructor; import java.lang.reflect.Field;public class ReflectDemo3 {/**Class對象功能:* 獲取功能:1. 獲取成員變量們* Field[] getFields()* Field getField(String name)* Field[] getDeclaredFields()* Field getDeclaredField(String name)2. 獲取構(gòu)造方法們* Constructor<?>[] getConstructors()* Constructor<T> getConstructor(類<?>... parameterTypes)* Constructor<T> getDeclaredConstructor(類<?>... parameterTypes)* Constructor<?>[] getDeclaredConstructors()3. 獲取成員方法們:* Method[] getMethods()* Method getMethod(String name, 類<?>... parameterTypes)* Method[] getDeclaredMethods()* Method getDeclaredMethod(String name, 類<?>... parameterTypes)4. 獲取類名* String getName()*/public static void main(String[] args) throws Exception {//0.獲取Person的Class對象Class personClass = Person.class;/*2. 獲取構(gòu)造方法們* Constructor<?>[] getConstructors()* Constructor<T> getConstructor(類<?>... parameterTypes)* Constructor<T> getDeclaredConstructor(類<?>... parameterTypes)* Constructor<?>[] getDeclaredConstructors()*///Constructor<T> getConstructor(類<?>... parameterTypes)Constructor constructor = personClass.getConstructor(String.class, int.class);System.out.println(constructor);//創(chuàng)建對象Object person = constructor.newInstance("張三", 23);System.out.println(person);System.out.println("----------");Constructor constructor1 = personClass.getConstructor();System.out.println(constructor1);//創(chuàng)建對象Object person1 = constructor1.newInstance();System.out.println(person1);Object o = personClass.newInstance();System.out.println(o);//constructor1.setAccessible(true);}}?
總結(jié)
以上是生活随笔為你收集整理的反射_Class对象功能_获取Constructor的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 反射_Class对象功能_获取Field
- 下一篇: 反射_Class对象功能_获取Metho