Java Reflection Constructor Invoke invokeExactConstructor(Class klass, Object arg)

Here you can find the source of invokeExactConstructor(Class klass, Object arg)

Description

Convenience method returning new instance of klazz using a single argument constructor.

License

Apache License

Parameter

Parameter Description
klass the class to be constructed.
arg the actual argument

Exception

Parameter Description
NoSuchMethodException If the constructor cannot be found
IllegalAccessException If an error occurs accessing the constructor
InvocationTargetException If an error occurs invoking the constructor
InstantiationException If an error occurs instantiating the class

Return

new instance of klazz

Declaration

public static Object invokeExactConstructor(Class klass, Object arg) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException 

Method Source Code


//package com.java2s;
/*/*from w w  w. j ava  2 s.  c  o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    /** An empty class array */
    private static final Class[] EMPTY_CLASS_PARAMETERS = new Class[0];
    /** An empty object array */
    private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];

    /**
     * <p>Convenience method returning new instance of <code>klazz</code> using a single argument constructor.
     * The formal parameter type is inferred from the actual values of <code>arg</code>.
     * See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.</p>
     *
     * <p>The signatures should match exactly.</p>
     *
     * @param klass the class to be constructed.
     * @param arg the actual argument
     * @return new instance of <code>klazz</code>
     *
     * @throws NoSuchMethodException If the constructor cannot be found
     * @throws IllegalAccessException If an error occurs accessing the constructor
     * @throws InvocationTargetException If an error occurs invoking the constructor
     * @throws InstantiationException If an error occurs instantiating the class
     *
     * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
     */
    public static Object invokeExactConstructor(Class klass, Object arg) throws NoSuchMethodException,
            IllegalAccessException, InvocationTargetException, InstantiationException {

        Object[] args = { arg };
        return invokeExactConstructor(klass, args);

    }

    /**
     * <p>Returns new instance of <code>klazz</code> created using the actual arguments <code>args</code>.
     * The formal parameter types are inferred from the actual values of <code>args</code>.
     * See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.</p>
     *
     * <p>The signatures should match exactly.</p>
     *
     * @param klass the class to be constructed.
     * @param args actual argument array
     * @return new instance of <code>klazz</code>
     *
     * @throws NoSuchMethodException If the constructor cannot be found
     * @throws IllegalAccessException If an error occurs accessing the constructor
     * @throws InvocationTargetException If an error occurs invoking the constructor
     * @throws InstantiationException If an error occurs instantiating the class
     *
     * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
     */
    public static Object invokeExactConstructor(Class klass, Object[] args) throws NoSuchMethodException,
            IllegalAccessException, InvocationTargetException, InstantiationException {
        if (null == args) {
            args = EMPTY_OBJECT_ARRAY;
        }
        int arguments = args.length;
        Class parameterTypes[] = new Class[arguments];
        for (int i = 0; i < arguments; i++) {
            parameterTypes[i] = args[i].getClass();
        }
        return invokeExactConstructor(klass, args, parameterTypes);

    }

    /**
     * <p>Returns new instance of <code>klazz</code> created using constructor
     * with signature <code>parameterTypes</code> and actual arguments
     * <code>args</code>.</p>
     *
     * <p>The signatures should match exactly.</p>
     *
     * @param klass the class to be constructed.
     * @param args actual argument array
     * @param parameterTypes parameter types array
     * @return new instance of <code>klazz</code>
     *
     * @throws NoSuchMethodException if matching constructor cannot be found
     * @throws IllegalAccessException thrown on the constructor's invocation
     * @throws InvocationTargetException thrown on the constructor's invocation
     * @throws InstantiationException thrown on the constructor's invocation
     * @see Constructor#newInstance
     */
    public static Object invokeExactConstructor(Class klass, Object[] args, Class[] parameterTypes)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
            InstantiationException {

        if (args == null) {
            args = EMPTY_OBJECT_ARRAY;
        }

        if (parameterTypes == null) {
            parameterTypes = EMPTY_CLASS_PARAMETERS;
        }

        Constructor ctor = getAccessibleConstructor(klass, parameterTypes);
        if (null == ctor) {
            throw new NoSuchMethodException("No such accessible constructor on object: " + klass.getName());
        }
        return ctor.newInstance(args);

    }

    public static Constructor getAccessibleConstructor(Class klass, Class parameterType) {

        Class[] parameterTypes = { parameterType };
        return getAccessibleConstructor(klass, parameterTypes);

    }

    public static Constructor getAccessibleConstructor(Class klass, Class[] parameterTypes) {

        try {
            return getAccessibleConstructor(klass.getConstructor(parameterTypes));
        } catch (NoSuchMethodException e) {
            return (null);
        }

    }

    public static Constructor getAccessibleConstructor(Constructor ctor) {

        // Make sure we have a method to check
        if (ctor == null) {
            return (null);
        }

        // If the requested method is not public we cannot call it
        if (!Modifier.isPublic(ctor.getModifiers())) {
            return (null);
        }

        // If the declaring class is public, we are done
        Class clazz = ctor.getDeclaringClass();
        if (Modifier.isPublic(clazz.getModifiers())) {
            return (ctor);
        }

        // what else can we do?
        return null;

    }
}

Related

  1. invokeConstructor(final Constructor constructor, final Object... args)
  2. invokeConstructor(String className, Class[] paramTypes, Object[] paramValues)
  3. invokeConstructor(String className, Object... arguments)
  4. invokeConstructorOrFail(Constructor constructor, Object... args)
  5. invokeCtor(Constructor ctor, String str)
  6. invokePrivateConstructor(Class clazz)
  7. invokePrivateConstructor(Class classType)
  8. invokePrivateConstructor(Class clazz)
  9. invokeReflectConstruct(String className, Object[] parameter, Class[] args)