集册 Java实例教程 返回带有单个参数的构造函数。

返回带有单个参数的构造函数。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

606
返回带有单个参数的构造函数。

/*

 * Copyright (c) 2007-2016 AREasy Runtime

 *

 * This library, AREasy Runtime and API for BMC Remedy AR System, is free software ("Licensed Software");

 * you can redistribute it and/or modify it under the terms of the GNU Lesser General Public

 * License as published by the Free Software Foundation; either version 2.1 of the License,

 * or (at your option) any later version.

 *

 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;

 * including but not limited to, the implied warranty of MERCHANTABILITY, NONINFRINGEMENT,

 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

 */

//package com.nowjava;

import java.lang.reflect.Constructor;//from 时   代     Java  公  众  号 - nowjava.com


import java.lang.reflect.Modifier;


public class Main {

    /**

     * Returns a constructor with single argument.

     *

     * @param klass the class to be constructed

     * @return null if matching accessible constructor can not be found.

     * @see Class#getConstructor

     * @see #getAccessibleConstructor(java.lang.reflect.Constructor)

     */

    public static Constructor getAccessibleConstructor(Class klass,

            Class parameterType) {


        Class[] parameterTypes = { parameterType };

        return getAccessibleConstructor(klass, parameterTypes);


    }/**from n o w j a v a . c o m**/


    /**

     * Returns a constructor given a class and signature.

     *

     * @param klass          the class to be constructed

     * @param parameterTypes the parameter array

     * @return null if matching accessible constructor can not be found

     * @see Class#getConstructor

     * @see #getAccessibleConstructor(java.lang.reflect.Constructor)

     */

    public static Constructor getAccessibleConstructor(Class klass,

            Class[] parameterTypes) {


        try {

            return getAccessibleConstructor(klass

                    .getConstructor(parameterTypes));

        } catch (NoSuchMethodException e) {

            return (null);

        }


    }


    /**

     * Returns accessible version of the given constructor.

     *

     * @param ctor prototype constructor object.

     * @return <code>null</code> if accessible constructor can not be found.

     * @see java.lang.SecurityManager

     */

    public static Constructor getAccessibleConstructor(Constructor ctor) {


        // Make sure we have a method to check

        if (ctor == null) {

            return (null);

        }


        
展开阅读全文