Constructor构造函数

通过Class的getConstructors 可以取得类的所有构造函数定义。

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

如果知道构造函数的参数定义,可以直接取得对应的构造函数,如:

[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});

如果Reflection API找不到对应的构造函数,则抛出NoSuchMethodException异常。

1. 获取构造函数的参数定义

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

2. 使用构造函数定义创建实例

[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");

newInstance 的参数可以选,调用时参数个数必须和对应的Constructor 定义的参数个数一致。


--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-----------------------------------------------------------------------------------


你可能感兴趣的:(Constructor构造函数)