List of usage examples for java.lang.reflect Constructor setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.
From source file:org.apache.hadoop.hbase.util.JVMClusterUtil.java
/** * Creates a {@link RegionServerThread}. * Call 'start' on the returned thread to make it run. * @param c Configuration to use./*from www . j a va2 s . c o m*/ * @param cp consensus provider to use * @param hrsc Class to create. * @param index Used distinguishing the object returned. * @throws IOException * @return Region server added. */ public static JVMClusterUtil.RegionServerThread createRegionServerThread(final Configuration c, CoordinatedStateManager cp, final Class<? extends HRegionServer> hrsc, final int index) throws IOException { HRegionServer server; try { Constructor<? extends HRegionServer> ctor = hrsc.getConstructor(Configuration.class, CoordinatedStateManager.class); ctor.setAccessible(true); server = ctor.newInstance(c, cp); } catch (InvocationTargetException ite) { Throwable target = ite.getTargetException(); throw new RuntimeException("Failed construction of RegionServer: " + hrsc.toString() + ((target.getCause() != null) ? target.getCause().getMessage() : ""), target); } catch (Exception e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } return new JVMClusterUtil.RegionServerThread(server, index); }
From source file:Main.java
public static Constructor<?> findConstructorExact(Class<?> clazz, Class<?>... parameterTypes) { StringBuilder sb = new StringBuilder(clazz.getName()); sb.append(getParametersString(parameterTypes)); sb.append("#exact"); String fullConstructorName = sb.toString(); if (constructorCache.containsKey(fullConstructorName)) { Constructor<?> constructor = constructorCache.get(fullConstructorName); if (constructor == null) throw new NoSuchMethodError(fullConstructorName); return constructor; }/*from www .j av a2s . c om*/ try { Constructor<?> constructor = clazz.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); constructorCache.put(fullConstructorName, constructor); return constructor; } catch (NoSuchMethodException e) { constructorCache.put(fullConstructorName, null); throw new NoSuchMethodError(fullConstructorName); } }
From source file:org.apache.sqoop.accumulo.AccumuloTestCase.java
protected static MiniAccumuloCluster createMiniAccumuloCluster(File tempDir, String rootPassword) throws Exception { final String configImplClassName = "org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl", clusterImplClassName = "org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl"; try {//from w ww .j a va 2 s . com // Get the MiniAccumuloConfigImpl class Class<?> configImplClz = Class.forName(configImplClassName); // Get the (File,String) constructor Constructor<?> cfgConstructor = configImplClz.getConstructor(new Class[] { File.class, String.class }); Object configImpl = cfgConstructor.newInstance(tempDir, rootPassword); // Get setClasspathItems(String...) Method setClasspathItemsMethod = configImplClz.getDeclaredMethod("setClasspathItems", String[].class); // Get the classpath, removing problematic jars String classpath = getClasspath(new File(tempDir, "conf")); // Call the method setClasspathItemsMethod.invoke(configImpl, (Object) new String[] { classpath }); // Get the private MiniAccumuloCluster(MiniAccumuloConfigImpl constructor) Constructor<?> clusterConstructor = MiniAccumuloCluster.class.getDeclaredConstructor(configImplClz); // Make it accessible (since its private) clusterConstructor.setAccessible(true); Object clusterImpl = clusterConstructor.newInstance(configImpl); return MiniAccumuloCluster.class.cast(clusterImpl); } catch (Exception e) { // Couldn't load the 1.6 MiniAccumuloConfigImpl which has // the classpath control LOG.warn("Could not load 1.6 minicluster classes", e); return new MiniAccumuloCluster(tempDir, ACCUMULO_PASSWORD); } }
From source file:com.psiphon3.psiphonlibrary.WebViewProxySettings.java
@SuppressWarnings("rawtypes") private static boolean setWebkitProxyICS(Context ctx, String host, int port) { try {//w w w .j av a2s . com Class webViewCoreClass = Class.forName("android.webkit.WebViewCore"); Class proxyPropertiesClass = Class.forName("android.net.ProxyProperties"); if (webViewCoreClass != null && proxyPropertiesClass != null) { Method m = webViewCoreClass.getDeclaredMethod("sendStaticMessage", Integer.TYPE, Object.class); Constructor c = proxyPropertiesClass.getConstructor(String.class, Integer.TYPE, String.class); if (m != null && c != null) { m.setAccessible(true); c.setAccessible(true); Object properties = c.newInstance(host, port, null); // android.webkit.WebViewCore.EventHub.PROXY_CHANGED = 193; m.invoke(null, 193, properties); return true; } } } catch (Exception e) { MyLog.d("Exception setting WebKit proxy through android.webkit.Network: " + e.toString()); } catch (Error e) { MyLog.d("Exception setting WebKit proxy through android.webkit.Network: " + e.toString()); } return false; }
From source file:org.evosuite.setup.TestClusterUtils.java
public static void makeAccessible(Constructor<?> constructor) { if (!Modifier.isPublic(constructor.getModifiers()) || !Modifier.isPublic(constructor.getDeclaringClass().getModifiers())) { constructor.setAccessible(true); }/* ww w . j a va2s .c o m*/ }
From source file:com.buaa.cfs.utils.ReflectionUtils.java
/** * Create an object for the given class and initialize it from conf * * @param theClass class of which an object is created * @param conf Configuration/*from w ww.j a v a 2 s .c o m*/ * * @return a new object */ @SuppressWarnings("unchecked") public static <T> T newInstance(Class<T> theClass, Configuration conf) { 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); } setConf(result, conf); return result; }
From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java
/** * Given a JSONObject, unmarhall it to an instance of the given class. * * @param jsonObj JSON string to unmarshall. * @param cls Return an instance of this class. Must be either public class * or private static class. Inner class will not work. * @param <T> Same type as cls.//from w ww . j a v a 2 s . c o m * @return An instance of class given by cls. * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException */ public static <T> T JSONToObj(JSONObject jsonObj, Class<T> cls) { T result = null; try { Constructor<T> constructor = cls.getDeclaredConstructor(); constructor.setAccessible(true); result = (T) constructor.newInstance(); Iterator<?> i = jsonObj.keys(); while (i.hasNext()) { String k = (String) i.next(); Object val = jsonObj.get(k); try { Field field = cls.getField(k); Object converted = valToType(val, field.getGenericType()); if (converted == null) { if (!field.getType().isPrimitive()) { field.set(result, null); } else { throw new TypeMismatchException( String.format("Type %s cannot be set to null.", field.getType())); } } else { if (converted instanceof List && field.getType().isAssignableFrom(List.class)) { // Class can define their own favorite // implementation of List. In which case the field // still need to be defined as List, but it can be // initialized with a placeholder instance of any of // the List implementations (eg. ArrayList). Object existing = field.get(result); if (existing != null) { ((List<?>) existing).clear(); // Just because I don't want javac to complain // about unsafe operations. So I'm gonna use // more reflection, HA! Method addAll = existing.getClass().getMethod("addAll", Collection.class); addAll.invoke(existing, converted); } else { field.set(result, converted); } } else { field.set(result, converted); } } } catch (NoSuchFieldException e) { // Ignore. } catch (IllegalAccessException e) { // Ignore. } catch (IllegalArgumentException e) { // Ignore. } } } catch (JSONException e) { throw new ParserException(e); } catch (NoSuchMethodException e) { throw new ClassInstantiationException("Failed to retrieve constructor for " + cls.toString() + ", make sure it's not an inner class."); } catch (InstantiationException e) { throw new ClassInstantiationException(cls); } catch (IllegalAccessException e) { throw new ClassInstantiationException(cls); } catch (InvocationTargetException e) { throw new ClassInstantiationException(cls); } return result; }
From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java
/** * @param signature//from w w w . j a va 2 s .co m * the signature of method in same format as {@link #getConstructorSignature(Constructor)}. * * @return the {@link Constructor} for given signature. This constructor can have any visibility, i.e. we * can find even protected/private constructors. */ @SuppressWarnings("unchecked") public static <T> Constructor<T> getConstructorBySignature(Class<T> clazz, String signature) throws Exception { Assert.isNotNull(clazz); Assert.isNotNull(signature); // check all declared constructors for (Constructor<?> constructor : clazz.getDeclaredConstructors()) { if (getConstructorSignature(constructor).equals(signature)) { constructor.setAccessible(true); return (Constructor<T>) constructor; } } // not found return null; }
From source file:tech.sirwellington.alchemy.generator.ObjectGenerators.java
private static <T> T instantiate(Class<T> classOfT) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Constructor<T> defaultConstructor = classOfT.getDeclaredConstructor(); boolean originalAccessibility = defaultConstructor.isAccessible(); try {// w w w . j a v a 2s .co m defaultConstructor.setAccessible(true); return defaultConstructor.newInstance(); } finally { defaultConstructor.setAccessible(originalAccessibility); } }
From source file:ml.shifu.shifu.util.ClassUtils.java
public static <T> T newInstance(Class<T> clazz, Class<?>[] parameterClasses, Object[] parameters) { T result;/*from w w w. j a v a 2 s. c o m*/ try { @SuppressWarnings("unchecked") Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(clazz); if (meth == null) { meth = clazz.getDeclaredConstructor(parameterClasses); meth.setAccessible(true); CONSTRUCTOR_CACHE.put(clazz, meth); } result = meth.newInstance(parameters); } catch (Exception e) { throw new RuntimeException(e); } return result; }