Example usage for java.lang Class getConstructor

List of usage examples for java.lang Class getConstructor

Introduction

In this page you can find the example usage for java.lang Class getConstructor.

Prototype

@CallerSensitive
public Constructor<T> getConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Usage

From source file:Main.java

private static int getExifOrientation(String src) throws IOException {
    int orientation = 1;

    try {//ww  w  . j  a v  a  2s. com
        /**
         * if your are targeting only api level >= 5
         * ExifInterface exif = new ExifInterface(src);
         * orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
         */
        if (Build.VERSION.SDK_INT >= 5) {
            Class<?> exifClass = Class.forName("android.media.ExifInterface");
            Constructor<?> exifConstructor = exifClass.getConstructor(new Class[] { String.class });
            Object exifInstance = exifConstructor.newInstance(new Object[] { src });
            Method getAttributeInt = exifClass.getMethod("getAttributeInt",
                    new Class[] { String.class, int.class });
            Field tagOrientationField = exifClass.getField("TAG_ORIENTATION");
            String tagOrientation = (String) tagOrientationField.get(null);
            orientation = (Integer) getAttributeInt.invoke(exifInstance, new Object[] { tagOrientation, 1 });
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }

    return orientation;
}

From source file:azkaban.jobs.builtin.JavaJobRunnerMain.java

private static Constructor<?> getConstructor(Class<?> c, Class<?>... args) {
    try {/*from   www .  j a va 2s . com*/
        Constructor<?> cons = c.getConstructor(args);
        return cons;
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:com.espertech.esper.util.ConstructorHelper.java

private static Constructor getRegularConstructor(Class clazz, Class parameterTypes[]) {

    // Try to find the matching constructor
    try {//from ww w . j  a v  a 2 s  .  c o m
        Constructor ctor = clazz.getConstructor(parameterTypes);

        try {
            ctor.setAccessible(true);
        } catch (SecurityException se) {
            // No action
        }

        return ctor;
    } catch (NoSuchMethodException e) {
        // Thats ok
    }
    return null;
}

From source file:com.github.fge.jsonschema.library.KeywordBuilder.java

private static Constructor<? extends KeywordValidator> getConstructor(final String name,
        final Class<? extends KeywordValidator> c) {
    try {//from   w  w  w.  j  a  v a  2 s .  com
        return c.getConstructor(JsonNode.class);
    } catch (NoSuchMethodException ignored) {
        throw new IllegalArgumentException(
                BUNDLE.printf("noAppropriateConstructor", name, c.getCanonicalName()));
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.DatabaseFactory.java

/**
 * Gets a database connection from the specified properties.
 *
 * @param p The database properties.//  w  ww. ja  v  a  2 s .  c  o  m
 * @return A reference of the specified database engine.
 * @throws DatabaseFactoryException If the class specified does not exist or its not well implemented.
 */
public static DatabaseEngine getConnection(Properties p) throws DatabaseFactoryException {
    PdbProperties pdbProperties = new PdbProperties(p, true);
    AbstractDatabaseEngine de = null;

    final String engine = pdbProperties.getEngine();

    if (StringUtils.isBlank(engine)) {
        throw new DatabaseFactoryException("pdb.engine property is mandatory");
    }

    try {
        Class<?> c = Class.forName(engine);

        Constructor cons = c.getConstructor(PdbProperties.class);
        de = (AbstractDatabaseEngine) cons.newInstance(pdbProperties);

        Class<? extends AbstractTranslator> tc = de.getTranslatorClass();

        if (pdbProperties.isTranslatorSet()) {
            final Class<?> propertiesTranslator = Class.forName(pdbProperties.getTranslator());
            if (!AbstractTranslator.class.isAssignableFrom(propertiesTranslator)) {
                throw new DatabaseFactoryException("Provided translator does extend from AbstractTranslator.");
            }

            tc = (Class<? extends AbstractTranslator>) propertiesTranslator;
        }

        final Injector injector = Guice.createInjector(
                new PdbModule.Builder().withTranslator(tc).withPdbProperties(pdbProperties).build());
        injector.injectMembers(de);

        return de;
    } catch (DatabaseFactoryException e) {
        throw e;
    } catch (Exception e) {
        throw new DatabaseFactoryException(e);
    }
}

From source file:ClassUtils.java

/**
 * Helper for invoking a constructor with one parameter.
 * //from   w  ww.  j av  a  2s  .  co m
 * @param className Class of which an instance is to be allocated
 * @param param Parameter
 * @param paramClass Type of the parameter
 * @throws ClassNotFoundException
 * @throws SecurityException
 * @throws NoSuchMethodException
 * @throws IllegalArgumentException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
public static Object createObject(String className, Object param, Class paramClass)
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Class clazzImpl = ClassUtils.forName(className);
    Constructor ctor = clazzImpl.getConstructor(new Class[] { paramClass });
    Object instance = ctor.newInstance(new Object[] { param });
    return instance;
}

From source file:Main.java

static Object getInstanceByClass(Class<?> claz) {
    try {/*  w w w.  ja  v a2 s  . co  m*/
        if (claz == Long.class || claz == Integer.class || claz == Short.class || claz == Double.class
                || claz == Float.class || claz == Byte.class)
            return claz.getConstructor(String.class).newInstance("0");
        else
            return claz.newInstance();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:net.sourceforge.atunes.utils.ReflectionUtils.java

/**
 * Creates a new instance of a class with a default constructor or returns
 * null if any exception happens//from   www .  j  a  va  2  s  .co m
 * 
 * @param className
 * @return
 */
public static Object newInstance(final String className) {
    Class<?> clazz;
    try {
        clazz = Class.forName(className);
        return clazz.getConstructor((Class[]) null).newInstance((Object[]) null);
    } catch (ClassNotFoundException e) {
        Logger.error(e);
    } catch (IllegalArgumentException e) {
        Logger.error(e);
    } catch (SecurityException e) {
        Logger.error(e);
    } catch (InstantiationException e) {
        Logger.error(e);
    } catch (IllegalAccessException e) {
        Logger.error(e);
    } catch (InvocationTargetException e) {
        Logger.error(e);
    } catch (NoSuchMethodException e) {
        Logger.error(e);
    }
    return null;
}

From source file:ExceptionUtils.java

/**
 * Create a new Exception, setting the cause if possible.
 * @param clazz/*from w w  w  .j a  v  a  2  s .  co m*/
 * @param message
 * @param cause
 * @return A Throwable.
 */
public static Throwable createWithCause(Class clazz, String message, Throwable cause) {
    Throwable re = null;
    if (causesAllowed) {
        try {
            Constructor constructor = clazz.getConstructor(new Class[] { String.class, Throwable.class });
            re = (Throwable) constructor.newInstance(new Object[] { message, cause });
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            causesAllowed = false;
        }
    }
    if (re == null) {
        try {
            Constructor constructor = clazz.getConstructor(new Class[] { String.class });
            re = (Throwable) constructor.newInstance(new Object[] { message + " caused by " + cause });
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Error caused " + e); // should be impossible
        }
    }
    return re;
}

From source file:com.kbotpro.handlers.ScriptMetaDataManager.java

public static void loadScriptMetaData() {
    if (System.currentTimeMillis() - lastUpdated > 3600) { // One hour
        String xml = StaticStorage.serverCom.getScriptList();
        try {//from w  ww. ja  va 2  s .co m
            Document doc = new SAXBuilder().build(new StringReader(xml));
            List<ScriptMetaData> loadedScriptMetaData = new ArrayList<ScriptMetaData>();
            Element root = doc.getRootElement();
            for (Element script : (List<Element>) root.getChildren("script")) {
                if (script == null) {
                    continue;
                }
                List<Permission> permissionExceptions = new ArrayList<Permission>();
                final Element policyNode = script.getChild("spolicy");
                if (policyNode != null) {
                    for (Element permission : (List<Element>) policyNode.getChildren("permission")) {
                        String className = permission.getAttributeValue("classname");
                        try {
                            Class klass = ScriptMetaDataManager.class.forName(className);
                            final Constructor constructor = klass
                                    .getConstructor(new Class<?>[] { String.class, String.class });
                            final Permission perm = (Permission) constructor.newInstance(
                                    permission.getAttributeValue("name"),
                                    permission.getAttributeValue("actions"));
                            permissionExceptions.add(perm);
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        } catch (InvocationTargetException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        } catch (InstantiationException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        } catch (IllegalAccessException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        }

                    }
                }
                ScriptMetaData scriptMetaData = new ScriptMetaData(
                        Integer.parseInt(script.getAttributeValue("ID")), script.getAttributeValue("name"),
                        script.getAttributeValue("author"),
                        Integer.parseInt(script.getAttributeValue("downloads")),
                        StringEscapeUtils.unescapeXml(script.getChildText("description")),
                        script.getAttributeValue("category"), script.getAttributeValue("type"),
                        script.getAttributeValue("version"), Integer.parseInt(script.getAttributeValue("rev")),
                        Integer.parseInt(script.getAttributeValue("modifier")), permissionExceptions);
                loadedScriptMetaData.add(scriptMetaData);
            }
            ScriptMetaDataManager.loadedScriptMetaData = loadedScriptMetaData;
        } catch (JDOMException e) {
            Logger.getRootLogger().error("Exception: ", e); //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            Logger.getRootLogger().error("Exception: ", e); //To change body of catch statement use File | Settings | File Templates.
        }
    }
}