Example usage for java.lang Class getDeclaredConstructor

List of usage examples for java.lang Class getDeclaredConstructor

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:com.bt.download.android.gui.UniversalScanner.java

private static Uri nativeScanFile(Context context, String path) {
    try {/*from  ww w. j  av a2s .  c  o  m*/
        File f = new File(path);

        Class<?> clazz = Class.forName("android.media.MediaScanner");

        Constructor<?> mediaScannerC = clazz.getDeclaredConstructor(Context.class);
        Object scanner = mediaScannerC.newInstance(context);

        Field mClientF = clazz.getDeclaredField("mClient");
        mClientF.setAccessible(true);
        Object mClient = mClientF.get(scanner);

        Method scanSingleFileM = clazz.getDeclaredMethod("scanSingleFile", String.class, String.class,
                String.class);
        Uri fileUri = (Uri) scanSingleFileM.invoke(scanner, f.getAbsolutePath(), "external", "data/raw");
        int n = context.getContentResolver().delete(fileUri, null, null);
        if (n > 0) {
            LOG.debug("Deleted from Files provider: " + fileUri);
        }

        Field mNoMediaF = mClient.getClass().getDeclaredField("mNoMedia");
        mNoMediaF.setAccessible(true);
        mNoMediaF.setBoolean(mClient, false);

        // This is only for HTC (tested only on HTC One M8)
        try {
            Field mFileCacheF = clazz.getDeclaredField("mFileCache");
            mFileCacheF.setAccessible(true);
            mFileCacheF.set(scanner, new HashMap<String, Object>());
        } catch (Throwable e) {
            // no an HTC, I need some time to refactor this hack
        }

        Method doScanFileM = mClient.getClass().getDeclaredMethod("doScanFile", String.class, String.class,
                long.class, long.class, boolean.class, boolean.class, boolean.class);
        Uri mediaUri = (Uri) doScanFileM.invoke(mClient, f.getAbsolutePath(), null, f.lastModified(),
                f.length(), false, true, false);

        Method releaseM = clazz.getDeclaredMethod("release");
        releaseM.invoke(scanner);

        return mediaUri;

    } catch (Throwable e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.lenovo.tensorhusky.common.utils.ReflectionUtils.java

/**
 * Create an object for the given class and initialize it from conf
 *
 * @param theClass class of which an object is created
 * @return a new object//from   www .  j  a  v  a2s  . c om
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> theClass) {
    T result;
    try {
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
        if (meth == null) {
            meth = theClass.getDeclaredConstructor(EMPTY_ARRAY);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(theClass, meth);
        }
        result = meth.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.apache.hama.util.ReflectionUtils.java

/**
 * Create an instance with corresponded class and object values supplied.
 * Constructor//from w w w .  j  av a2 s. c o  m
 * 
 * @param theClass supplies instance to be created.
 * @param parameters are class type of object values supplied.
 * @param values are parameters applied when instance is created.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T newInstance(Class<T> theClass, Class[] parameters, Object[] values) {
    T result;
    try {
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
        if (null == meth) {
            meth = theClass.getDeclaredConstructor(parameters);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(theClass, meth);
        }
        result = meth.newInstance(values);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:science.atlarge.graphalytics.powergraph.Utils.java

public static <T> Map<Long, T> readResults(File f, Class<T> clazz) throws Exception {
    Map<Long, T> results = new HashMap<Long, T>();

    BufferedReader r = new BufferedReader(new FileReader(f));
    String line;/*w w w.  j av  a2s . c om*/

    while ((line = r.readLine()) != null) {
        String tokens[] = line.split(" ", 2);

        Long vertex = Long.valueOf(tokens[0]);
        T value = clazz.getDeclaredConstructor(String.class).newInstance(tokens[1]);
        results.put(vertex, value);
    }

    return results;
}

From source file:com.ery.server.util.ReflectionUtils.java

@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> theClass) {
    T result;/*from w ww  .  j  a  v a 2 s .c om*/
    try {
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
        if (meth == null) {
            meth = theClass.getDeclaredConstructor(EMPTY_ARRAY);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(theClass, meth);
        }
        result = meth.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.apache.hama.util.ReflectionUtils.java

@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> theClass) {
    Preconditions.checkNotNull(theClass);
    T result;//from  ww  w.  j a  v a2s. c  o m
    try {
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
        if (null == meth) {
            meth = theClass.getDeclaredConstructor(new Class[0]);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(theClass, meth);
        }
        result = meth.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.wikipedia.nirvana.statistics.StatisticsFabric.java

@SuppressWarnings("unchecked")
static Statistics createReporter(NirvanaWiki wiki, String type) {
    Statistics ob = null;/*w  w  w. j  ava  2  s.c  o m*/
    ob = reporters.get(type);
    if (ob == null) {
        Class cl = reporterClass.get(type);
        if (cl == null)
            return null;
        try {
            Class params[] = new Class[2];
            params[0] = NirvanaWiki.class;
            params[1] = String.class;
            ob = (Statistics) cl.getDeclaredConstructor(params).newInstance(wiki, type);
            reporters.put(type, ob);
        } catch (Exception e) {
            log.error(e);
        }
    }
    // NULL return value will tell about error         
    return ob;
}

From source file:com.expressui.core.util.ReflectionUtil.java

/**
 * Creates new instance from the given type, based on given parameter types and args.
 *
 * @param type           class to reflectively instantiate
 * @param <T>            type of the class
 * @param parameterTypes used to find the right constructor
 * @param args           passed to constructor
 * @return new instance//from ww w . jav  a 2s  .  c om
 */
public static <T> T newInstance(Class<T> type, Class[] parameterTypes, Object[] args) {
    try {
        Constructor constructor = type.getDeclaredConstructor(parameterTypes);
        constructor.setAccessible(true);
        return (T) constructor.newInstance(args);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wolvencraft.yasp.util.Util.java

/**
 * Composes a list of active modules for the player
 *
 * @param session Player session//from  w  ww .  j  a v a  2 s .co m
 * @return List of modules
 */
@SuppressWarnings("rawtypes")
public static List<DataStore> getModules(OnlineSession session) {
    List<DataStore> dataStores = new ArrayList<DataStore>();
    for (Module module : Module.values()) {
        if (module.isHook() || !module.isActive())
            continue;
        for (Class<? extends DataStore> store : module.getDataStores()) {
            DataStore storeObj = null;
            try {
                storeObj = store.getDeclaredConstructor(OnlineSession.class).newInstance(session);
            } catch (Throwable t) {
                ExceptionHandler.handle(t);
            }
            if (storeObj == null)
                continue;
            dataStores.add(storeObj);
        }
    }
    return dataStores;
}

From source file:com.wolvencraft.yasp.util.Util.java

/**
 * Composes a list of active plugin hooks for the player
 *
 * @param session Player session/*from   w  w  w. j  av  a 2  s  .c om*/
 * @return List of plugin hooks
 */
@SuppressWarnings("rawtypes")
public static List<DataStore> getHooks(OnlineSession session) {
    List<DataStore> dataStores = new ArrayList<DataStore>();
    for (Module module : Module.values()) {
        if (!module.isHook() || !module.isActive())
            continue;
        for (Class<? extends DataStore> store : module.getDataStores()) {
            DataStore storeObj = null;
            try {
                storeObj = store.getDeclaredConstructor(OnlineSession.class).newInstance(session);
            } catch (Throwable t) {
                ExceptionHandler.handle(t);
            }
            if (storeObj == null)
                continue;
            dataStores.add(storeObj);
        }
    }
    return dataStores;
}