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.eclipse.wb.internal.core.model.description.helpers.ComponentDescriptionHelper.java
/** * Adds {@link ConstructorDescription} for given {@link ComponentDescription}. */// w ww .j a v a2 s . c o m private static void addConstructors(IJavaProject javaProject, ComponentDescription componentDescription) throws Exception { Class<?> componentClass = componentDescription.getComponentClass(); for (Constructor<?> constructor : componentClass.getDeclaredConstructors()) { constructor.setAccessible(true); ConstructorDescription constructorDescription = new ConstructorDescription(componentClass); // add parameter descriptions of constructor for (Class<?> parameterType : constructor.getParameterTypes()) { addParameter(constructorDescription, parameterType); } // OK, add constructor description constructorDescription.postProcess(); componentDescription.addConstructor(constructorDescription); } }
From source file:org.unitils.util.ReflectionUtils.java
/** * Creates an instance of the given type * //from w ww.j av a2 s .co m * @param <T> * The type of the instance * @param type * The type of the instance * @param bypassAccessibility * If true, no exception is thrown if the parameterless * constructor is not public * @param argumentTypes * The constructor arg types, not null * @param arguments * The constructor args, not null * @return An instance of this type * @throws UnitilsException * If an instance could not be created */ public static <T> T createInstanceOfType(Class<T> type, boolean bypassAccessibility, Class[] argumentTypes, Object[] arguments) { if (type.isMemberClass() && !isStatic(type.getModifiers())) { throw new UnitilsException( "Creation of an instance of a non-static innerclass is not possible using reflection. The type " + type.getSimpleName() + " is only known in the context of an instance of the enclosing class " + type.getEnclosingClass().getSimpleName() + ". Declare the innerclass as static to make construction possible."); } try { Constructor<T> constructor = type.getDeclaredConstructor(argumentTypes); if (bypassAccessibility) { constructor.setAccessible(true); } return constructor.newInstance(arguments); } catch (InvocationTargetException e) { throw new UnitilsException("Error while trying to create object of class " + type.getName(), e.getCause()); } catch (Exception e) { throw new UnitilsException("Error while trying to create object of class " + type.getName(), e); } }
From source file:info.guardianproject.netcipher.web.WebkitProxy.java
private static boolean setWebkitProxyICS(Context ctx, String host, int port) { // PSIPHON: added support for Android 4.x WebView proxy try {//from ww w. jav a 2 s .c om 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) { Log.e("ProxySettings", "Exception setting WebKit proxy through android.net.ProxyProperties: " + e.toString()); } catch (Error e) { Log.e("ProxySettings", "Exception setting WebKit proxy through android.webkit.Network: " + e.toString()); } return false; }
From source file:Main.java
public static Constructor<?> findConstructorBestMatch(Class<?> clazz, Class<?>... parameterTypes) { StringBuilder sb = new StringBuilder(clazz.getName()); sb.append(getParametersString(parameterTypes)); sb.append("#bestmatch"); String fullConstructorName = sb.toString(); if (constructorCache.containsKey(fullConstructorName)) { Constructor<?> constructor = constructorCache.get(fullConstructorName); if (constructor == null) throw new NoSuchMethodError(fullConstructorName); return constructor; }// ww w . ja v a 2s.c om try { Constructor<?> constructor = findConstructorExact(clazz, parameterTypes); constructorCache.put(fullConstructorName, constructor); return constructor; } catch (NoSuchMethodError ignored) { } Constructor<?> bestMatch = null; Constructor<?>[] constructors = clazz.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { // compare name and parameters // if (ClassUtils.isAssignable(parameterTypes, constructor.getParameterTypes(), true)) { // // get accessible version of method // if (bestMatch == null || MemberUtils.compareParameterTypes( // constructor.getParameterTypes(), // bestMatch.getParameterTypes(), // parameterTypes) < 0) { // bestMatch = constructor; // } // } } if (bestMatch != null) { bestMatch.setAccessible(true); constructorCache.put(fullConstructorName, bestMatch); return bestMatch; } else { NoSuchMethodError e = new NoSuchMethodError(fullConstructorName); constructorCache.put(fullConstructorName, null); throw e; } }
From source file:com.github.dactiv.common.utils.ReflectionUtils.java
/** * ?constructorannotationClass/* w w w . j av a 2s.c o m*/ * * @param constructor * constructor * @param annotationClass * annotationClass * * @return {@link Annotation} */ public static <T extends Annotation> T getAnnotation(Constructor constructor, Class annotationClass) { Assert.notNull(constructor, "constructor?"); Assert.notNull(annotationClass, "annotationClass?"); constructor.setAccessible(true); if (constructor.isAnnotationPresent(annotationClass)) { return (T) constructor.getAnnotation(annotationClass); } return null; }
From source file:com.li.utils.ui.mdbottom.BottomNavigation.java
static BadgeProvider parseBadgeProvider(final BottomNavigation navigation, final Context context, final String name) { if (TextUtils.isEmpty(name)) { return new BadgeProvider(navigation); }/*w w w .j av a 2s.c o m*/ final String fullName; if (name.startsWith(".")) { fullName = context.getPackageName() + name; } else if (name.indexOf('.') >= 0) { fullName = name; } else { // Assume stock behavior in this package (if we have one) fullName = !TextUtils.isEmpty(WIDGET_PACKAGE_NAME) ? (WIDGET_PACKAGE_NAME + '.' + name) : name; } try { Map<String, Constructor<BadgeProvider>> constructors = S_CONSTRUCTORS.get(); if (constructors == null) { constructors = new HashMap<>(); S_CONSTRUCTORS.set(constructors); } Constructor<BadgeProvider> c = constructors.get(fullName); if (c == null) { final Class<BadgeProvider> clazz = (Class<BadgeProvider>) Class.forName(fullName, true, context.getClassLoader()); c = clazz.getConstructor(CONSTRUCTOR_PARAMS); c.setAccessible(true); constructors.put(fullName, c); } return c.newInstance(navigation); } catch (Exception e) { throw new RuntimeException("Could not inflate Behavior subclass " + fullName, e); } }
From source file:org.apache.empire.db.DBReader.java
/** * copied from org.apache.commons.beanutils.ConstructorUtils since it's private there */// ww w . j a va 2s.c o m @SuppressWarnings("unchecked") private static Constructor findMatchingAccessibleConstructor(Class clazz, Class[] parameterTypes) { // See if we can find the method directly // probably faster if it works // (I am not sure whether it's a good idea to run into Exceptions) // try { // Constructor ctor = clazz.getConstructor(parameterTypes); // try { // // see comment in org.apache.commons.beanutils.ConstructorUtils // ctor.setAccessible(true); // } catch (SecurityException se) { /* ignore */ } // return ctor; // } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all constructors int paramSize = parameterTypes.length; Constructor[] ctors = clazz.getConstructors(); for (int i = 0, size = ctors.length; i < size; i++) { // compare parameters Class[] ctorParams = ctors[i].getParameterTypes(); int ctorParamSize = ctorParams.length; if (ctorParamSize == paramSize) { // Param Size matches boolean match = true; for (int n = 0; n < ctorParamSize; n++) { if (!ObjectUtils.isAssignmentCompatible(ctorParams[n], parameterTypes[n])) { match = false; break; } } if (match) { // get accessible version of method Constructor ctor = ConstructorUtils.getAccessibleConstructor(ctors[i]); if (ctor != null) { try { ctor.setAccessible(true); } catch (SecurityException se) { /* ignore */ } return ctor; } } } } return null; }
From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java
private static Constructor<?> getConstructor(Class<?> clazz) { Constructor<?> res; Constructor<?>[] constructors = clazz.getDeclaredConstructors(); if (constructors.length == 0) { throw new ITestInitializationException(clazz, null); }/*w w w .j a va 2 s .c om*/ res = constructors[0]; for (int i = 1; i < constructors.length; i++) { if (constructors[i].getParameterTypes().length == 0) { res = constructors[i]; break; } } try { res.setAccessible(true); } catch (SecurityException e) { throw new ITestInitializationException(clazz, e); } return res; }
From source file:it.sephiroth.android.library.bottomnavigation.BottomNavigation.java
static BadgeProvider parseBadgeProvider(final BottomNavigation navigation, final Context context, final String name) { log(TAG, INFO, "parseBadgeProvider: %s", name); if (TextUtils.isEmpty(name)) { return new BadgeProvider(navigation); }/*w ww. j a v a 2 s. co m*/ final String fullName; if (name.startsWith(".")) { fullName = context.getPackageName() + name; } else if (name.indexOf('.') >= 0) { fullName = name; } else { // Assume stock behavior in this package (if we have one) fullName = !TextUtils.isEmpty(WIDGET_PACKAGE_NAME) ? (WIDGET_PACKAGE_NAME + '.' + name) : name; } try { Map<String, Constructor<BadgeProvider>> constructors = S_CONSTRUCTORS.get(); if (constructors == null) { constructors = new HashMap<>(); S_CONSTRUCTORS.set(constructors); } Constructor<BadgeProvider> c = constructors.get(fullName); if (c == null) { final Class<BadgeProvider> clazz = (Class<BadgeProvider>) Class.forName(fullName, true, context.getClassLoader()); c = clazz.getConstructor(CONSTRUCTOR_PARAMS); c.setAccessible(true); constructors.put(fullName, c); } return c.newInstance(navigation); } catch (Exception e) { throw new RuntimeException("Could not inflate Behavior subclass " + fullName, e); } }
From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java
/** * Gets the serialization constructor for the given class based on the given * base class. The specified base class is expected to have a default constructor * to use for initializing the hierarchy from that point on. The constructor * can have any visibility (i.e. public, protected, package private, or private). * <p>// ww w.j a v a 2 s .c o m * <i>Note:</i> The returned constructor results in having a proper object of * the given class instantiated without calling any of the constructors from * its class or super classes. The fields of all classes in the hierarchy will * not be initialized; thus set using default Java initialization (i.e. * <code>null</code>, 0, 0L, false, ...). This is how Java creates new * serialized objects before calling the <code>readObject()</code> method of * each of the subclasses. * * @author paouelle * * @param <T> the class for which to get the serialization constructor * * @param clazz the class for which to get the serialization constructor * @param bclass the base class to start the initialization from in the * returned serialization constructor * @return the non-<code>null</code> serialization constructor for the given * class * @throws NullPointerException if <code>clazz</code> or <code>bclass</code> * is <code>null</code> * @throws IllegalArgumentException if <code>bclass</code> is not a base class * for <code>clazz</code> * @throws SecurityException if the request is denied */ public static <T> Constructor<T> getSerializationConstructorFromBaseClass(Class<T> clazz, Class<?> bclass) { org.apache.commons.lang3.Validate.notNull(clazz, "invalid null class"); org.apache.commons.lang3.Validate.notNull(bclass, "invalid null base class"); org.apache.commons.lang3.Validate.isTrue(bclass.isAssignableFrom(clazz), bclass.getName() + " is not a superclass of " + clazz.getName()); final Constructor<?> ctor; try { // find the default ctor for the base class ctor = bclass.getDeclaredConstructor(); ctor.setAccessible(true); } catch (NoSuchMethodException e) { throw new IllegalStateException("missing default constructor for base class: " + bclass.getName(), e); } @SuppressWarnings({ "restriction", "unchecked" }) final Constructor<T> nc = (Constructor<T>) ReflectionUtils.reflFactory.newConstructorForSerialization(clazz, ctor); nc.setAccessible(true); return nc; }