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.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java

public MultiplexArgumentTypeDescriptor createCustomTypeDescriptor(ParsingEngine parsingEngine,
        ArgumentSource dependentArgument, Object containingObject) {
    String[] sourceFields = dependentArgument.field.getAnnotation(Multiplex.class).arguments();

    List<ArgumentSource> allSources = parsingEngine.extractArgumentSources(containingObject.getClass());
    Class[] sourceTypes = new Class[sourceFields.length];
    Object[] sourceValues = new Object[sourceFields.length];
    int currentField = 0;

    for (String sourceField : sourceFields) {
        boolean fieldFound = false;
        for (ArgumentSource source : allSources) {
            if (!source.field.getName().equals(sourceField))
                continue;
            if (source.field.isAnnotationPresent(Multiplex.class))
                throw new ReviewedStingException(
                        "Command-line arguments can only depend on independent fields");
            sourceTypes[currentField] = source.field.getType();
            sourceValues[currentField] = JVMUtils.getFieldValue(source.field, containingObject);
            currentField++;//  w w  w  . j av  a 2 s .  c o  m
            fieldFound = true;
        }
        if (!fieldFound)
            throw new ReviewedStingException(
                    String.format("Unable to find source field %s, referred to by dependent field %s",
                            sourceField, dependentArgument.field.getName()));
    }

    Class<? extends Multiplexer> multiplexerType = dependentArgument.field.getAnnotation(Multiplex.class)
            .value();
    Constructor<? extends Multiplexer> multiplexerConstructor;
    try {
        multiplexerConstructor = multiplexerType.getConstructor(sourceTypes);
        multiplexerConstructor.setAccessible(true);
    } catch (NoSuchMethodException ex) {
        throw new ReviewedStingException(
                String.format("Unable to find constructor for class %s with parameters %s",
                        multiplexerType.getName(), Arrays.deepToString(sourceFields)),
                ex);
    }

    Multiplexer multiplexer;
    try {
        multiplexer = multiplexerConstructor.newInstance(sourceValues);
    } catch (IllegalAccessException ex) {
        throw new ReviewedStingException(
                String.format("Constructor for class %s with parameters %s is inaccessible",
                        multiplexerType.getName(), Arrays.deepToString(sourceFields)),
                ex);
    } catch (InstantiationException ex) {
        throw new ReviewedStingException(String.format("Can't create class %s with parameters %s",
                multiplexerType.getName(), Arrays.deepToString(sourceFields)), ex);
    } catch (InvocationTargetException ex) {
        throw new ReviewedStingException(
                String.format("Can't invoke constructor of class %s with parameters %s",
                        multiplexerType.getName(), Arrays.deepToString(sourceFields)),
                ex);
    }

    return new MultiplexArgumentTypeDescriptor(multiplexer, multiplexer.multiplex());
}

From source file:org.catrobat.catroid.uitest.util.UiTestUtils.java

public static void showAndFilloutNewSpriteDialogWithoutClickingOk(Solo solo, String spriteName, Uri uri,
        ActionAfterFinished actionToPerform, SpinnerAdapterWrapper spinner) {
    if (!(solo.getCurrentActivity() instanceof FragmentActivity)) {
        fail("Current activity is not a FragmentActivity");
    }/*from   ww w  .  java2  s.  c  om*/

    FragmentManager fragmentManager = ((FragmentActivity) solo.getCurrentActivity())
            .getSupportFragmentManager();

    NewSpriteDialog dialog;

    // create dialog and skip step 1 (choosing an image)
    try {
        Constructor<NewSpriteDialog> constructor = NewSpriteDialog.class.getDeclaredConstructor(
                DialogWizardStep.class, Uri.class, String.class, ActionAfterFinished.class,
                SpinnerAdapterWrapper.class);
        constructor.setAccessible(true);
        dialog = constructor.newInstance(DialogWizardStep.STEP_2, uri, spriteName, actionToPerform, spinner);
    } catch (Exception e) {
        Log.e(TAG, "Reflection failure.", e);
        fail("Reflection failure");
        return;
    }

    dialog.show(fragmentManager, NewSpriteDialog.DIALOG_FRAGMENT_TAG);

    EditText addNewSpriteEditText = solo.getEditText(0);

    //check if hint is set
    String hintString = addNewSpriteEditText.getHint().toString();
    assertEquals("Not the proper hint set", true, hintString.startsWith(spriteName));
    assertEquals("There should no text be set", "", addNewSpriteEditText.getText().toString());
    solo.enterText(0, spriteName);
}

From source file:com.nttec.everychan.ui.theme.CustomThemeHelper.java

private View instantiate(String name, Context context, AttributeSet attrs) {
    try {/* www.  j  av  a2s  . com*/
        Constructor<? extends View> constructor = CONSTRUCTOR_MAP.get(name);
        if (constructor == null) {
            Class<? extends View> clazz = null;
            if (name.indexOf('.') != -1) {
                clazz = context.getClassLoader().loadClass(name).asSubclass(View.class);
            } else {
                for (String prefix : CLASS_PREFIX_LIST) {
                    try {
                        clazz = context.getClassLoader().loadClass(prefix + name).asSubclass(View.class);
                        break;
                    } catch (ClassNotFoundException e) {
                    }
                }
                if (clazz == null)
                    throw new ClassNotFoundException("couldn't find class: " + name);
            }
            constructor = clazz.getConstructor(CONSTRUCTOR_SIGNATURE);
            CONSTRUCTOR_MAP.put(name, constructor);
        }

        Object[] args = constructorArgs;
        args[0] = context;
        args[1] = attrs;

        constructor.setAccessible(true);
        View view = constructor.newInstance(args);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && view instanceof ViewStub)
            CompatibilityImpl.setLayoutInflater((ViewStub) view, inflater.cloneInContext(context));
        return view;
    } catch (Exception e) {
        Logger.e(TAG, "couldn't instantiate class " + name, e);
        return null;
    }
}

From source file:com.taobao.adfs.distributed.DistributedServer.java

void createData() throws IOException {
    String dataPath = getDataPath(conf);
    try {//from w  ww  .  j a va 2 s  .c  o  m
        String dataClassName = conf.get("distributed.data.class.name");
        if (dataClassName == null)
            throw new IOException("distributed.data.class.name is not specified");
        Class<?> dataClass = Class.forName(dataClassName);
        Constructor<?> dataConstructor = dataClass.getDeclaredConstructor(Configuration.class,
                ReentrantReadWriteLockExtension.class);
        dataConstructor.setAccessible(true);
        data = (DistributedData) dataConstructor.newInstance(conf, getDataLocker);
        if (conf.getBoolean("distributed.data.initialize.result", false))
            serverType = ServerType.ONLINE;
        else
            serverType = ServerType.NEED_RESTORE;
        log(Level.INFO, " create data with path=", dataPath);
    } catch (Throwable t) {
        Utilities.logError(logger, " fail to create data with path=", dataPath, t);
        throw new IOException(t);
    }
}

From source file:org.powertac.logtool.common.DomainObjectReader.java

private Object constructInstance(Class<?> clazz, String[] args) throws MissingDomainObject {
    Constructor<?>[] potentials = clazz.getDeclaredConstructors();
    Constructor<?> target = null;
    Object[] params = null;//from   w  ww .  j  a  v  a 2 s  .  co m
    for (Constructor<?> cons : potentials) {
        Type[] types = cons.getGenericParameterTypes();
        if (types.length != args.length)
            // not this one
            continue;
        // correct length of parameter list -
        // now try to resolve the types.
        // If we get a MissingDomainObject exception, keep going.
        try {
            params = resolveArgs(types, args);
        } catch (MissingDomainObject mdo) {
            // ignore
        }
        if (null == params)
            // no match
            continue;
        else {
            target = cons;
            break;
        }
    }
    // if we found one, use it, then update the id value
    if (null != target) {
        Object result = null;
        try {
            target.setAccessible(true);
            result = target.newInstance(params);
        } catch (InvocationTargetException ite) {
            // arg-constructor mismatch
            return restoreInstance(clazz, args);
        } catch (Exception e) {
            log.error("could not construct instance of " + clazz.getName() + ": " + e.toString());
            return null;
        }
        return result;
    } else {
        // otherwise, try to use the readResolve method
        return restoreInstance(clazz, args);
    }
}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsActionTest.java

public void testGetItemForNumberFormate() throws Exception {
    String language = "en";
    String concept = "Goods";
    String ids = "1";
    ViewBean viewBean = getViewBean(concept, "GoodsWithNumberField.xsd");
    ItemBean item = new ItemBean(concept, ids, getXml("GoodsWithNumberFieldSample.xml"));
    if (item.getOriginalMap() == null) {
        item.setOriginalMap(new HashMap<String, Object>());
    }/*from  w  ww. ja v a 2 s. c om*/
    if (item.getFormateMap() == null) {
        item.setFormateMap(new HashMap<String, String>());
    }

    com.amalto.core.delegator.BeanDelegatorContainer beanDelegatorContainer = PowerMockito
            .spy(com.amalto.core.delegator.BeanDelegatorContainer.createInstance());
    Whitebox.<BeanDelegatorContainer>invokeMethod(beanDelegatorContainer, "getInstance");
    BeanDelegatorContainer.getInstance().setDelegatorInstancePool(
            Collections.<String, Object>singletonMap("LocalUser", new MockILocalUser()));
    //LocalUser localUser = PowerMockito.spy(new LocalUser());
    Whitebox.<BeanDelegatorContainer>invokeMethod(beanDelegatorContainer, "setDelegatorInstancePool",
            Collections.<String, Object>singletonMap("LocalUser", new MockILocalUser()));
    Whitebox.<LocalUser>invokeMethod(beanDelegatorContainer, "getLocalUserDelegator");

    PowerMockito.when(LocalUser.getLocalUser()).thenReturn(new MockILocalUser());
    String[] roles = { "Demo_Manager", "System_Admin", "authenticated", "administration" };
    HashSet<String> rolesSet = new HashSet<String>();
    rolesSet.addAll(Arrays.asList(roles));

    Constructor<Configuration> constructor = Configuration.class.getDeclaredConstructor(String.class,
            String.class);
    constructor.setAccessible(true);
    Configuration config = constructor.newInstance(concept, concept);

    PowerMockito.mockStatic(Configuration.class);
    Mockito.when(Configuration.getConfiguration()).thenReturn(config);

    XtentisPort port = PowerMockito.mock(XtentisPort.class);
    PowerMockito.spy(org.talend.mdm.webapp.base.server.util.CommonUtil.class);
    PowerMockito.doReturn(port).when(org.talend.mdm.webapp.base.server.util.CommonUtil.class, "getPort");
    WSItem wsItem = getWsItem(concept, concept, ids, getXml("GoodsWithNumberFieldSample.xml"));
    Mockito.when(port.getItem(Mockito.any(WSGetItem.class))).thenReturn(wsItem);

    ItemBean itemBean = action.getItem(item, null, viewBean.getBindingEntityModel(), false, language);

    Map<String, Object> originalMap = itemBean.getOriginalMap();
    Map<String, String> formateMap = itemBean.getFormateMap();

    assertEquals(4, originalMap.size());
    assertEquals(4, formateMap.size());

    assertEquals("5.5000", formateMap.get("Goods/doubleValue").toString());
    assertEquals("1.50000000", formateMap.get("Goods/decimalValue").toString());
    assertEquals("4.5000", formateMap.get("Goods/simpleDecimalValue").toString());
    assertEquals("2.0000", formateMap.get("Goods/floatValue").toString());

    assertEquals("5.5", originalMap.get("Goods/doubleValue").toString());
    assertEquals("1.5", originalMap.get("Goods/decimalValue").toString());
    assertEquals("4.5", originalMap.get("Goods/simpleDecimalValue").toString());
    assertEquals("2", originalMap.get("Goods/floatValue").toString());
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

private Object getNewInstanceObjectAnnotated(String ref, Object... args) {
    Object ret = null;//from w  ww  . ja va  2 s  .c  o m
    try {
        for (Class in : ClassScan.findAll().annotatedWith(Adialog.class).recursively()
                .in(conf.get("path_gui").toString(), "com.m4rc310.gui")) {
            Adialog ad = (Adialog) in.getDeclaredAnnotation(Adialog.class);
            if (ad.ref().equals(ref)) {
                if (ret != null) {
                    throw new Exception(String.format("H mais de uma classe refernciada como [%s]!", ref));
                }

                Class[] types = new Class[args.length];

                Constructor constructor = null;
                for (int i = 0; i < args.length; i++) {
                    types[i] = args[i].getClass();
                    Class type = args[i].getClass();
                    for (Class ai : type.getInterfaces()) {
                        try {
                            constructor = in.getDeclaredConstructor(ai);
                            break;
                        } catch (NoSuchMethodException | SecurityException e) {
                            infoError(e);
                        }
                    }
                }

                constructor = constructor == null ? in.getDeclaredConstructor(types) : constructor;

                //                    Constructor constructor = in.getDeclaredConstructor(types);
                constructor.setAccessible(true);
                ret = constructor.newInstance(args);
            }
        }
        return ret;
    } catch (Exception e) {
        infoError(e);
        throw new UnsupportedOperationException(e);
    }
}

From source file:com.mantz_it.rfanalyzer.ui.activity.MainActivity.java

/**
 * Reflection-based source settings updater
 *
 * @param clazz desired class of source/*from   w w w. j  a v a 2 s.c  o m*/
 * @return current source with updated settings, or new source if current source type isn't instance of desired source.
 */
protected void updateSourcePreferences(final Class<?> clazz) {
    // if src is of desired class -- just update
    if (clazz.isInstance(this.source)) {
        setSource(this.source.updatePreferences(this, preferences));
        analyzerSurface.setSource(this.source);
    } else {
        // create new
        this.source.close();
        final String msg;
        try {
            // we can't force sources to implement constructor with needed parameters,
            // to drop need of tracking all sources that could be added later just use reflection
            // to call constructor with current Context and SharedPreferences and let source configure itself
            Constructor ctor = clazz.getDeclaredConstructor(Context.class, SharedPreferences.class);
            ctor.setAccessible(true);
            setSource((IQSource) ctor.newInstance(this, preferences));
            analyzerSurface.setSource(this.source);
            return;
        } catch (NoSuchMethodException e) {
            Log.e(LOGTAG, "updateSourcePreferences: "
                    + (msg = "selected source doesn't have constructor with demanded parameters (Context, SharedPreferences)"));
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            Log.e(LOGTAG, "updateSourcePreferences: "
                    + (msg = "selected source doesn't have accessible constructor with demanded parameters (Context, SharedPreferences)"));
            e.printStackTrace();
        } catch (InstantiationException e) {
            Log.e(LOGTAG, "updateSourcePreferences: "
                    + (msg = "selected source doesn't have accessible for MainActivity constructor with demanded parameters (Context, SharedPreferences)"));
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            Log.e(LOGTAG, "updateSourcePreferences: "
                    + (msg = "source's constructor thrown exception: " + e.getMessage()));
            e.printStackTrace();
        }
        stopAnalyzer();
        this.runOnUiThread(
                () -> toaster.showLong("Error with instantiating source [" + clazz.getName() + "]: "));
        setSource(null);
    }
}

From source file:com.github.helenusdriver.driver.impl.ClassInfoImpl.java

/**
 * Finds all final fields in this class and all super classes up to and
 * excluding the first class that is not annotated with the corresponding
 * entity annotation./*from  w ww.  j a  v a2  s .  c  o  m*/
 *
 * @author paouelle
 *
 * @return a non-<code>null</code> map of all final fields and their default
 *         values
 */
private Map<Field, Object> findFinalFields() {
    final Map<Field, Object> ffields = new HashMap<>(8);
    MutableObject<Object> obj = null; // lazy evaluated

    // go up the hierarchy until we hit the class for which we have a default
    // serialization constructor as that class will have its final fields
    // properly initialized by the ctor whereas all others will have their final
    // fields initialized with 0, false, null, ...
    for (Class<? super T> clazz = this.clazz; clazz != constructor.getDeclaringClass(); clazz = clazz
            .getSuperclass()) {
        for (final Field field : clazz.getDeclaredFields()) {
            final int mods = field.getModifiers();

            if (Modifier.isFinal(mods) && !Modifier.isStatic(mods)) {
                field.setAccessible(true); // so we can access its value directly
                if (obj == null) {
                    // instantiates a dummy version and access its value
                    try {
                        // find default ctor even if private
                        final Constructor<T> ctor = this.clazz.getDeclaredConstructor();

                        ctor.setAccessible(true); // in case it was private
                        final T t = ctor.newInstance();

                        obj = new MutableObject<>(t);
                    } catch (NoSuchMethodException | IllegalAccessException | InstantiationException e) {
                        throw new IllegalArgumentException(
                                "unable to instantiate object: " + this.clazz.getName(), e);
                    } catch (InvocationTargetException e) {
                        final Throwable t = e.getTargetException();

                        if (t instanceof Error) {
                            throw (Error) t;
                        } else if (t instanceof RuntimeException) {
                            throw (RuntimeException) t;
                        } else { // we don't expect any of those
                            throw new IllegalArgumentException(
                                    "unable to instantiate object: " + this.clazz.getName(), t);
                        }
                    }
                }
                try {
                    ffields.put(field, field.get(obj.getValue()));
                } catch (IllegalAccessException e) {
                    throw new IllegalArgumentException("unable to access final value for field: "
                            + field.getDeclaringClass().getName() + "." + field.getName(), e);
                }
            }
        }
    }
    return ffields;
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * If the field is defined as final then finds and encode its default value.
 *
 * @author paouelle/* w w w  .j a v  a2  s  .  c  om*/
 *
 * @return the encoded default value for this field or <code>null</code> if the
 *         field is not defined as final
 * @throws IllegalArgumentException if the field is final and we are unable to
 *         instantiate a dummy version of the pojo or access the field's final
 *         value or again we failed to encode it
 *         encode its default value
 */
private Object findFinalValue() {
    if (isFinal) {
        Object val;

        try {
            val = cinfo.getDefaultValue(field);
        } catch (IllegalArgumentException e) {
            // final field was not introspected by class info (declared class
            // must not be annotated with @Entity)
            // instantiates a dummy version and access its value
            try {
                // find default ctor even if private
                final Constructor<T> ctor = clazz.getDeclaredConstructor();

                ctor.setAccessible(true); // in case it was private
                final T t = ctor.newInstance();

                val = field.get(t);
            } catch (NoSuchMethodException | IllegalAccessException | InstantiationException ee) {
                throw new IllegalArgumentException("unable to instantiate object: " + clazz.getName(), ee);
            } catch (InvocationTargetException ee) {
                final Throwable t = ee.getTargetException();

                if (t instanceof Error) {
                    throw (Error) t;
                } else if (t instanceof RuntimeException) {
                    throw (RuntimeException) t;
                } else { // we don't expect any of those
                    throw new IllegalArgumentException("unable to instantiate object: " + clazz.getName(), t);
                }
            }
        }
        if (persister != null) { // must encode it using the persister
            final String fname = declaringClass.getName() + "." + name;

            try {
                val = definition.encode(val, persisted, persister, fname);
            } catch (IOException e) {
                throw new IllegalArgumentException("failed to encode final field '" + fname + "' to "
                        + persisted.as().CQL + "' with persister: " + persister.getClass().getName(), e);
            }
        }
        return val;
    }
    return null;
}