Constructor構造函數

經過Class的getConstructors 能夠取得類的全部構造函數定義。 java

[java] Class aClass = ...//obtain class object  
Constructor[] constructors = aClass.getConstructors(); 
Class aClass = ...//obtain class object
Constructor[] constructors = aClass.getConstructors(); ide

若是知道構造函數的參數定義,能夠直接取得對應的構造函數,如: 函數

[java]
Class aClass = ...//obtain class object  
Constructor constructor = 
 aClass.getConstructor(new Class[]{String.class}); 
Class aClass = ...//obtain class object
Constructor constructor =
 aClass.getConstructor(new Class[]{String.class}); ui

若是Reflection API找不到對應的構造函數,則拋出NoSuchMethodException異常。 get

1. 獲取構造函數的參數定義 it

[java]
Class[] parameterTypes = constructor.getParameterTypes(); 
Class[] parameterTypes = constructor.getParameterTypes(); io

2. 使用構造函數定義建立實例 class

[java]
//get constructor that takes a String as argument  
Constructor constructor = MyObject.class.getConstructor(String.class); 
  
MyObject myObject = (MyObject) 
 constructor.newInstance("constructor-arg1"); 
//get constructor that takes a String as argument
Constructor constructor = MyObject.class.getConstructor(String.class);
 
MyObject myObject = (MyObject)
 constructor.newInstance("constructor-arg1"); object

newInstance 的參數能夠選,調用時參數個數必須和對應的Constructor 定義的參數個數一致。 sso


--Source---------------------------------------------------------------------------------

public T newInstance(Object ... initargs)
    throws InstantiationException, IllegalAccessException,
               IllegalArgumentException, InvocationTargetException
    {
        if (!override) {
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                Class caller = Reflection.getCallerClass(2);
                if (securityCheckCache != caller) {
                    Reflection.ensureMemberAccess(caller, clazz, null, modifiers);
                    securityCheckCache = caller;
                }
            }
        }
    if ((clazz.getModifiers() & Modifier.ENUM) != 0)
        throw new IllegalArgumentException("Cannot reflectively create enum objects");
        if (constructorAccessor == null) acquireConstructorAccessor();
        return (T) constructorAccessor.newInstance(initargs);
    }

adapter = (FileAdapterBase)clazz.getConstructor(types).newInstance(args);

--Source-----------------------------------------------------------------------------------

相關文章
相關標籤/搜索