Example usage for java.lang.reflect Constructor setAccessible

List of usage examples for java.lang.reflect Constructor setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Constructor setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Document

A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.

Usage

From source file:org.evosuite.setup.TestClusterGenerator.java

protected static void makeAccessible(Constructor<?> constructor) {
    if (!Modifier.isPublic(constructor.getModifiers())
            || !Modifier.isPublic(constructor.getDeclaringClass().getModifiers())) {
        constructor.setAccessible(true);
    }/*  w w  w  .j  a v  a 2 s  .  com*/
}

From source file:org.fluentlenium.core.Fluent.java

protected <T extends FluentPage> T constructPageWithParams(Class<T> cls, Object[] params)
        throws NoSuchMethodException, InstantiationException, IllegalAccessException,
        InvocationTargetException {
    T page;/*from   www. jav  a2  s . com*/
    Class<?>[] classTypes = new Class[params.length];
    for (int i = 0; i < params.length; i++) {
        classTypes[i] = params[i].getClass();
    }

    try {
        Constructor<T> construct = cls.getDeclaredConstructor(classTypes);

        construct.setAccessible(true);
        page = construct.newInstance(params);
        return page;
    } catch (NoSuchMethodException ex) {
        if (params.length != 0) {
            throw new ConstructionException("You provided the wrong arguments to the createPage method, "
                    + "if you just want to use a page with a default constructor, use @Page or createPage("
                    + cls.getSimpleName() + ".class)", ex);
        } else {
            throw ex;
        }
    }
}

From source file:hu.bme.mit.sette.common.model.snippet.SnippetContainer.java

/**
 * Validates the constructor of the class.
 *
 * @param validator//w  w  w .  j  av a2 s .  c o  m
 *            a validator
 */
private void validateConstructor(final AbstractValidator<?> validator) {
    if (javaClass.getDeclaredConstructors().length != 1) {
        // constructor count is validated with the class
        return;
    }

    Constructor<?> constructor = javaClass.getDeclaredConstructors()[0];
    ConstructorValidator v = new ConstructorValidator(constructor);
    v.withModifiers(Modifier.PRIVATE).parameterCount(0);
    v.synthetic(false);

    // check: constructor throws new
    // UnsupportedOperationException("Static class")

    Throwable exception = null;
    try {
        // call the private ctor
        constructor.setAccessible(true);
        constructor.newInstance();
    } catch (Exception e) {
        exception = e.getCause();
    } finally {
        // restore visibility
        constructor.setAccessible(false);
    }

    if (exception == null || !exception.getClass().equals(UnsupportedOperationException.class)
            || !exception.getMessage().equals("Static class")) {
        v.addException("The constructor must throw an " + "UnsupportedOperationException with "
                + "the message \"Static class\"");
    }

    validator.addChildIfInvalid(v);
}

From source file:android.support.v7.app.AppCompatViewInflater.java

private View createView(Context context, String name, String prefix)
        throws ClassNotFoundException, InflateException {
    Constructor<? extends View> constructor = sConstructorMap.get(name);

    try {/*  ww  w  .  java 2s. c o  m*/
        if (constructor == null) {
            // Class not found in the cache, see if it's real, and try to add it
            Class<? extends View> clazz = context.getClassLoader()
                    .loadClass(prefix != null ? (prefix + name) : name).asSubclass(View.class);

            constructor = clazz.getConstructor(sConstructorSignature);
            sConstructorMap.put(name, constructor);
        }
        constructor.setAccessible(true);
        return constructor.newInstance(mConstructorArgs);
    } catch (Exception e) {
        // We do not want to catch these, lets return null and let the actual LayoutInflater
        // try
        return null;
    }
}

From source file:org.opensingular.flow.core.ProcessDefinition.java

@Nonnull
private I newUnbindedInstance() {
    I novo;//from w  w w  .  j av a  2  s. c  o m
    try {
        for (Constructor<?> c : getProcessInstanceClass().getDeclaredConstructors()) {
            if (c.getParameters().length == 0) {
                c.setAccessible(true);
                novo = (I) c.newInstance();
                novo.setProcessDefinition(this);
                return novo;
            }
        }
    } catch (Exception e) {
        throw new SingularFlowException(e.getMessage(), e);
    }
    throw new SingularFlowException(
            createErrorMsg(
                    "Construtor sem parametros ausente: " + getProcessInstanceClass().getSimpleName() + "()"),
            this);
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

private Object instantiateService(ClassLoader cl, String className, String[] parms)
        throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {
    Class clazz = Class.forName(className, true, cl);
    log.log(Level.FINE, MessageNames.CLASSLOADER_IS,
            new Object[] { clazz.getName(), clazz.getClassLoader().toString() });

    // Get this through dynamic lookup becuase it won't be in the parent
    // classloader!
    Class lifeCycleClass = Class.forName(Strings.LIFECYCLE_CLASS, true, cl);
    Constructor[] constructors = clazz.getDeclaredConstructors();
    System.out.println("Class is " + clazz);
    for (int i = 0; i < constructors.length; i++) {
        Constructor constructor = constructors[i];
        System.out.println("Found constructor " + constructor + " on " + className);
    }//  w ww  . j  a v  a  2 s.  c  o  m
    Constructor constructor = clazz.getDeclaredConstructor(new Class[] { String[].class, lifeCycleClass });
    constructor.setAccessible(true);
    return constructor.newInstance(parms, null);
}

From source file:org.apache.sentry.api.service.thrift.SentryPolicyStoreProcessor.java

public static Set<String> getGroupsFromUserName(Configuration conf, String userName)
        throws SentryUserException {
    String groupMapping = conf.get(ServerConfig.SENTRY_STORE_GROUP_MAPPING,
            ServerConfig.SENTRY_STORE_GROUP_MAPPING_DEFAULT);
    String authResoruce = conf.get(ServerConfig.SENTRY_STORE_GROUP_MAPPING_RESOURCE);

    // load the group mapping provider class
    GroupMappingService groupMappingService;
    try {/*from ww w .j  a va  2 s  .com*/
        Constructor<?> constrctor = Class.forName(groupMapping).getDeclaredConstructor(Configuration.class,
                String.class);
        constrctor.setAccessible(true);
        groupMappingService = (GroupMappingService) constrctor.newInstance(new Object[] { conf, authResoruce });
    } catch (NoSuchMethodException e) {
        throw new SentryUserException("Unable to instantiate group mapping", e);
    } catch (SecurityException e) {
        throw new SentryUserException("Unable to instantiate group mapping", e);
    } catch (ClassNotFoundException e) {
        throw new SentryUserException("Unable to instantiate group mapping", e);
    } catch (InstantiationException e) {
        throw new SentryUserException("Unable to instantiate group mapping", e);
    } catch (IllegalAccessException e) {
        throw new SentryUserException("Unable to instantiate group mapping", e);
    } catch (IllegalArgumentException e) {
        throw new SentryUserException("Unable to instantiate group mapping", e);
    } catch (InvocationTargetException e) {
        throw new SentryUserException("Unable to instantiate group mapping", e);
    }
    return groupMappingService.getGroups(userName);
}

From source file:org.leo.benchmark.Benchmark.java

/**
 * Run the benchmark on the given collection
 * /*from   w  w w .j a v a  2 s . com*/
 * @param collectionTested the collection (if it's a List, some additional
 *            bench will be done)
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void run(Class<? extends Collection> collectionClass) {
    try {
        long startTime = System.currentTimeMillis();
        Constructor<? extends Collection> constructor = collectionClass
                .getDeclaredConstructor((Class<?>[]) null);
        constructor.setAccessible(true);
        collection = (Collection<String>) constructor.newInstance();
        System.out.println("Performances of " + collection.getClass().getCanonicalName() + " populated with "
                + populateSize + " elt(s)");
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

        // some collection used in some benchmark cases
        final Collection<String> col = new ArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            col.add(Integer.toString(i % 30));
        }

        // Collection benchmark
        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.add(Integer.toString(i % 29));
            }
        }, populateSize, "add " + populateSize + " elements");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.remove(Integer.toString(i));
            }
        }, Math.max(1, populateSize / 10),
                "remove " + Math.max(1, populateSize / 10) + " elements given Object");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.addAll(col);
            }
        }, Math.min(populateSize, 1000),
                "addAll " + Math.min(populateSize, 1000) + " times " + col.size() + " elements");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.contains(collection.size() - i - 1);
            }
        }, Math.min(populateSize, 1000), "contains " + Math.min(populateSize, 1000) + " times");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.removeAll(col);
            }
        }, Math.min(populateSize, 10),
                "removeAll " + Math.min(populateSize, 10) + " times " + col.size() + " elements");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.iterator();
            }
        }, populateSize, "iterator " + populateSize + " times");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.containsAll(col);
            }
        }, Math.min(populateSize, 5000), "containsAll " + Math.min(populateSize, 5000) + " times");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.toArray();
            }
        }, Math.min(populateSize, 5000), "toArray " + Math.min(populateSize, 5000) + " times");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.clear();
            }
        }, 1, "clear");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.retainAll(col);
            }
        }, Math.min(populateSize, 10), "retainAll " + Math.min(populateSize, 10) + " times");

        // List benchmark
        if (collection instanceof List) {
            list = (List<String>) collection;
            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.add((i), Integer.toString(i));
                }
            }, populateSize, "add at a given index " + populateSize + " elements");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.addAll((i), col);
                }
            }, Math.min(populateSize, 1000), "addAll " + Math.min(populateSize, 1000) + " times " + col.size()
                    + " elements at a given index");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.get(i);
                }
            }, Math.min(populateSize, 50000), "get " + Math.min(populateSize, 50000) + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.indexOf(i);
                }
            }, Math.min(populateSize, 5000), "indexOf " + Math.min(populateSize, 5000) + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.lastIndexOf(i);
                }
            }, Math.min(populateSize, 5000), "lastIndexOf " + Math.min(populateSize, 5000) + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.set(i, Integer.toString(i % 29));
                }
            }, Math.max(1, populateSize), "set " + Math.max(1, populateSize) + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.subList(collection.size() / 4, collection.size() / 2);
                }
            }, populateSize, "subList on a " + (populateSize / 2 - populateSize / 4) + " elts sublist "
                    + populateSize + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.listIterator();
                }
            }, populateSize, "listIterator " + populateSize + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.listIterator(i);
                }
            }, populateSize, "listIterator at a given index " + populateSize + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.remove(list.size() / 2);
                }
            }, 10000, "remove " + 10000 + " elements given index (index=list.size()/2)");
        }

        System.out.println(
                "Benchmark done in " + ((double) (System.currentTimeMillis() - startTime)) / 1000 + "s");
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        // free memory
        collection.clear();
    } catch (Exception e) {
        System.err.println("Failed running benchmark on class " + collectionClass.getCanonicalName());
        e.printStackTrace();
    }
    collection = null;
    list = null;
    heavyGc();
}

From source file:com.hyc.skin.core.SkinViewInflater.java

private View createView(Context context, String name, String prefix)
        throws ClassNotFoundException, InflateException {
    Constructor<? extends View> constructor = sConstructorMap.get(name);
    //Log.e("hyc-test-end",name);
    try {/*from   ww w.  j  a v a 2  s.c  o m*/
        if (constructor == null) {
            // Class not found in the cache, see if it's real, and try to add it
            Class<? extends View> clazz = context.getClassLoader()
                    .loadClass(prefix != null ? (prefix + name) : name).asSubclass(View.class);

            constructor = clazz.getConstructor(sConstructorSignature);
            sConstructorMap.put(name, constructor);
        }
        constructor.setAccessible(true);
        return constructor.newInstance(mConstructorArgs);
    } catch (Exception e) {
        // We do not want to catch these, lets return null and let the actual LayoutInflater
        // try
        return null;
    }
}

From source file:de.xaniox.heavyspleef.core.flag.FlagRegistry.java

public void registerFlag(Class<? extends AbstractFlag<?>> clazz, I18NSupplier i18nSupplier, Object cookie) {
    Validate.notNull(clazz, "clazz cannot be null");
    Validate.isTrue(!isFlagPresent(clazz), "Cannot register flag twice: " + clazz.getName());

    if (i18nSupplier == null) {
        i18nSupplier = GLOBAL_SUPPLIER;/*from   w  w  w  . ja va 2s .  c  om*/
    }

    /* Check if the class provides the required Flag annotation */
    Validate.isTrue(clazz.isAnnotationPresent(Flag.class),
            "Flag-Class must be annotated with the @Flag annotation");

    Flag flagAnnotation = clazz.getAnnotation(Flag.class);
    String name = flagAnnotation.name();

    Validate.isTrue(!name.isEmpty(),
            "name() of annotation of flag for class " + clazz.getCanonicalName() + " cannot be empty");

    /* Generate a path */
    StringBuilder pathBuilder = new StringBuilder();
    Flag parentFlagData = flagAnnotation;

    do {
        pathBuilder.insert(0, parentFlagData.name());

        Class<? extends AbstractFlag<?>> parentFlagClass = parentFlagData.parent();
        parentFlagData = parentFlagClass.getAnnotation(Flag.class);

        if (parentFlagData != null && parentFlagClass != NullFlag.class) {
            pathBuilder.insert(0, FLAG_PATH_SEPERATOR);
        }
    } while (parentFlagData != null);

    String path = pathBuilder.toString();

    /* Check for name collides */
    for (String flagPath : registeredFlagsMap.primaryKeySet()) {
        if (flagPath.equalsIgnoreCase(path)) {
            throw new IllegalArgumentException("Flag " + clazz.getName() + " collides with "
                    + registeredFlagsMap.get(flagPath).flagClass.getName());
        }
    }

    /* Check if the class can be instantiated */
    try {
        Constructor<? extends AbstractFlag<?>> constructor = clazz.getDeclaredConstructor();

        //Make the constructor accessible for future uses
        constructor.setAccessible(true);
    } catch (NoSuchMethodException | SecurityException e) {
        throw new IllegalArgumentException("Flag-Class must provide an empty constructor");
    }

    FlagClassHolder holder = new FlagClassHolder();
    holder.flagClass = clazz;
    holder.supplier = i18nSupplier;
    holder.cookie = cookie;

    Field[] instanceInjectableFields = null;

    if (checkHooks(flagAnnotation)) {
        inject(holder, null, null);
        instanceInjectableFields = getInjectableDeclaredFieldsByFilter(clazz,
                new FieldFilter(FieldFilter.INSTANCE_MODE));

        if (initializationPolicy == InitializationPolicy.COMMIT) {
            Method[] initMethods = getInitMethods(holder);
            for (Method method : initMethods) {
                queuedInitMethods.offer(method);
            }
        } else if (initializationPolicy == InitializationPolicy.REGISTER) {
            runInitMethods(holder);
        }

        if (flagAnnotation.hasCommands()) {
            CommandManager manager = heavySpleef.getCommandManager();
            manager.registerSpleefCommands(clazz);
        }

        holder.staticFieldsInjected = true;
        holder.staticMethodsInitialized = true;
    }

    holder.injectingFields = instanceInjectableFields;
    registeredFlagsMap.put(path, flagAnnotation, holder);

    if (heavySpleef.isGamesLoaded()) {
        for (Game game : heavySpleef.getGameManager().getGames()) {
            for (AbstractFlag<?> flag : game.getFlagManager().getFlags()) {
                if (!(flag instanceof UnloadedFlag)) {
                    continue;
                }

                UnloadedFlag unloaded = (UnloadedFlag) flag;
                if (!unloaded.getFlagName().equals(path)) {
                    continue;
                }

                game.removeFlag(path);

                AbstractFlag<?> newFlag = newFlagInstance(path, AbstractFlag.class, game);
                newFlag.unmarshal(unloaded.getXmlElement());

                game.addFlag(newFlag);
            }
        }
    }
}