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.HashMap;
import java.util.Map;

public class Main {
    private static final Map<Class<?>, Object> INSTANCE_MAP = new HashMap<>();

    @SuppressWarnings("unchecked")
    public static final <E> E getInstance(Class<E> clazz) {
        if (INSTANCE_MAP.containsKey(clazz)) {
            return (E) INSTANCE_MAP.get(clazz);
        } else {
            E instance;
            synchronized (clazz) {
                instance = (E) INSTANCE_MAP.get(clazz);
                if (instance == null) {
                    try {
                        Constructor<E> constructor = clazz.getDeclaredConstructor();
                        constructor.setAccessible(true);
                        instance = constructor.newInstance();
                        INSTANCE_MAP.put(clazz, instance);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
            return instance;
        }
    }
}