Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;

public class Main {
    public static <T> Collection<T> getObjectsOfType(Collection<?> input, Class<T> type) {
        return getObjectsOfType(input, type, null);
    }

    public static <T> Collection<T> getObjectsOfType(Collection<?> input, Class<T> type, Collection<T> output) {
        if (output == null) {
            output = createEmpty(input);
            if (output == null)
                output = new ArrayList<T>();
        }
        for (Object o : input) {
            if (type.isAssignableFrom(o.getClass()))
                output.add((T) o);
        }
        return output;
    }

    /**
     * Creates a new empty instance of the provided collection
     * 
     * @param <T>
     * @param in
     * @return
     */
    public static <T> Collection<T> createEmpty(Collection<?> in) {
        Class<?> originalClass = in.getClass();
        try {
            Constructor<?> originalConstructor = originalClass.getConstructor(new Class[0]);
            return (Collection<T>) originalConstructor.newInstance(new Object[0]);
        } catch (IllegalArgumentException e) {
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        } finally {
            return null;
        }
    }
}