Java Class New Instance newInstance(Class clazz)

Here you can find the source of newInstance(Class clazz)

Description

Tries to invoke Foo.getInstance() if the method (public+static) getInstance() is there; If not, it creates a new instance via reflection.

License

Apache License

Declaration

public static Object newInstance(Class<?> clazz) throws InstantiationException, IllegalAccessException 

Method Source Code


//package com.java2s;
//Licensed under the Apache License, Version 2.0 (the "License");

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    static final String GET_INSTANCE = "getInstance";
    private static final Class<?>[] __emptyArg = new Class<?>[] {};
    private static final Object[] __getterArg = new Object[] {};

    /**/*from w w w  .  j ava  2 s. c  o m*/
     * Tries to invoke Foo.getInstance() if the method (public+static) getInstance() is there; 
     * If not, it creates a new instance via reflection.
     */
    public static Object newInstance(Class<?> clazz) throws InstantiationException, IllegalAccessException {
        Object o = getInstance(clazz);
        return o == null ? clazz.newInstance() : o;
    }

    /**
     * Tries to invoke Foo.getInstance() if the method (public+static) getInstance() is there.
     */
    public static Object getInstance(Class<?> clazz) {
        Method m = null;
        try {
            m = clazz.getDeclaredMethod(GET_INSTANCE, __emptyArg);
        } catch (Exception e) {
            try {
                m = clazz.getDeclaredMethod("get" + clazz.getSimpleName(), __emptyArg);
            } catch (Exception e1) {
                return null;
            }
        }
        if (m != null && Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) {
            try {
                return m.invoke(null, __getterArg);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}

Related

  1. newInstance(Class clazz)
  2. newInstance(Class componentType, int length)
  3. newInstance(Class classZ)
  4. newInstance(Class clazz)
  5. newInstance(Class clazz)
  6. newInstance(Class clazz)
  7. newInstance(Class clazz)
  8. newInstance(Class clazz)
  9. newInstance(Class clazz)