集册 Java实例教程 从构造器构造实例

从构造器构造实例

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

427
从构造器构造实例

/**
 from
* N o w  J a v a  .   c o m 
**/

//package com.nowjava;

import java.util.ArrayList;

import java.util.List;


public class Main {

    public static <T> List<T> constructInstances(

            Class<? extends T>[] classes, Class<? extends T> def) {


        List<T> result = new ArrayList<T>();

        if (classes == null || classes.length == 0) {

            if (def != null) {

                result.add(createObject(def));

            }

        } else {

            for (Class<? extends T> cls : classes) {

                result.add(createObject(cls));

            }

        }

        return result;
        /** from 
        时 代 J a v a 公 众 号**/

    }


    public static <T> T createObject(Class<? extends T> cls, Class<?> arg) {


        try {

            return cls.getConstructor(Class.class).newInstance(arg);

        } catch (Exception exc) {

            throw new RuntimeException(exc);

        }

    }


    static <T> T createObject(Class<? 
展开阅读全文