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:gov.anl.cue.arcane.engine.matrix.MatrixModel.java
/** * Run the matrix model./* www . ja va 2 s . c om*/ * * @return the double */ public Double runMatrixModel() { // Create a results holder. Double results = Double.NaN; // Attempt to run the model. try { // Setup a temporary class loader. URL[] urls = new URL[] { new File(Util.TEMP_DIR).toURI().toURL() }; URLClassLoader classLoader = new URLClassLoader(urls, null, null); // Attempt to load the compiled file. @SuppressWarnings("rawtypes") Constructor constructor = classLoader .loadClass(MatrixModel.PACKAGE_NAME + "." + MatrixModel.CONCRETE_CLASS_NAME) .getDeclaredConstructor(double.class); constructor.setAccessible(true); Object object = constructor.newInstance(this.stepSize); // Call "matrixFormulation.step(steps)". Method method = object.getClass().getSuperclass().getMethod("step", int.class); method.invoke(object, this.stepCount); // Call matrixFormulation.calculateFitnessValue(); method = object.getClass().getSuperclass().getMethod("calculateFitnessValue"); results = (Double) method.invoke(object); // Clear the given class loader, which should not be // a child of another class loader. object = null; method = null; classLoader.close(); ResourceBundle.clearCache(classLoader); classLoader = null; Introspector.flushCaches(); System.runFinalization(); System.gc(); // Catch exceptions. } catch (Exception e) { // Return the default result. results = Double.NaN; } // Return the results. return results; }
From source file:org.apache.geode.internal.InternalDataSerializer.java
/** * Instantiates an instance of {@code DataSerializer} * * @throws IllegalArgumentException If the class can't be instantiated * * @see DataSerializer#register(Class)//w w w . j a va2 s . c o m */ private static DataSerializer newInstance(Class c) { if (!DataSerializer.class.isAssignableFrom(c)) { throw new IllegalArgumentException(LocalizedStrings.DataSerializer_0_DOES_NOT_EXTEND_DATASERIALIZER .toLocalizedString(c.getName())); } Constructor init; try { init = c.getDeclaredConstructor(new Class[0]); } catch (NoSuchMethodException ignored) { StringId s = LocalizedStrings.DataSerializer_CLASS_0_DOES_NOT_HAVE_A_ZEROARGUMENT_CONSTRUCTOR; Object[] args = new Object[] { c.getName() }; if (c.getDeclaringClass() != null) { s = LocalizedStrings.DataSerializer_CLASS_0_DOES_NOT_HAVE_A_ZEROARGUMENT_CONSTRUCTOR_IT_IS_AN_INNER_CLASS_OF_1_SHOULD_IT_BE_A_STATIC_INNER_CLASS; args = new Object[] { c.getName(), c.getDeclaringClass() }; } throw new IllegalArgumentException(s.toLocalizedString(args)); } DataSerializer s; try { init.setAccessible(true); s = (DataSerializer) init.newInstance(new Object[0]); } catch (IllegalAccessException ignored) { throw new IllegalArgumentException( LocalizedStrings.DataSerializer_COULD_NOT_INSTANTIATE_AN_INSTANCE_OF_0 .toLocalizedString(c.getName())); } catch (InstantiationException ex) { throw new IllegalArgumentException( LocalizedStrings.DataSerializer_COULD_NOT_INSTANTIATE_AN_INSTANCE_OF_0 .toLocalizedString(c.getName()), ex); } catch (InvocationTargetException ex) { throw new IllegalArgumentException(LocalizedStrings.DataSerializer_WHILE_INSTANTIATING_AN_INSTANCE_OF_0 .toLocalizedString(c.getName()), ex); } return s; }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * Construct a class//from w ww . j a v a2 s . c o m * @param <T> template type * @param theClass * @param allowPrivateConstructor true if should allow private constructors * @return the instance */ public static <T> T newInstance(Class<T> theClass, boolean allowPrivateConstructor) { if (!allowPrivateConstructor) { return newInstance(theClass); } try { Constructor<?>[] constructorArray = theClass.getDeclaredConstructors(); for (Constructor<?> constructor : constructorArray) { if (constructor.getGenericParameterTypes().length == 0) { if (allowPrivateConstructor) { constructor.setAccessible(true); } return (T) constructor.newInstance(); } } //why cant we find a constructor??? throw new RuntimeException("Why cant we find a constructor for class: " + theClass); } catch (Throwable e) { if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) { throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!", e); } throw new RuntimeException("Problem with class: " + theClass, e); } }
From source file:com.codename1.impl.android.AndroidImplementation.java
private String getUserAgent() { try {// ww w . j a v a 2s. co m String userAgent = System.getProperty("http.agent"); if (userAgent != null) { return userAgent; } } catch (Exception e) { } if (getActivity() == null) { return "Android-CN1"; } try { Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class, WebView.class); constructor.setAccessible(true); try { WebSettings settings = constructor.newInstance(getActivity(), null); return settings.getUserAgentString(); } finally { constructor.setAccessible(false); } } catch (Exception e) { final StringBuffer ua = new StringBuffer(); if (Thread.currentThread().getName().equalsIgnoreCase("main")) { WebView m_webview = new WebView(getActivity()); ua.append(m_webview.getSettings().getUserAgentString()); m_webview.destroy(); } else { final boolean[] flag = new boolean[1]; Thread thread = new Thread() { public void run() { Looper.prepare(); WebView m_webview = new WebView(getActivity()); ua.append(m_webview.getSettings().getUserAgentString()); m_webview.destroy(); Looper.loop(); flag[0] = true; synchronized (flag) { flag.notify(); } } }; thread.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler); thread.start(); while (!flag[0]) { synchronized (flag) { try { flag.wait(100); } catch (InterruptedException ex) { } } } } return ua.toString(); } }
From source file:android.support.v71.widget.RecyclerView.java
/** * Instantiate and set a LayoutManager, if specified in the attributes. * LayotManager// w w w .j av a2 s . c o m */ private void createLayoutManager(Context context, String className, AttributeSet attrs, int defStyleAttr, int defStyleRes) { if (className != null) { className = className.trim(); if (className.length() != 0) { // Can't use isEmpty since it was added in API 9. className = getFullClassName(context, className); try { ClassLoader classLoader; if (isInEditMode()) { // Stupid layoutlib cannot handle simple class loaders. classLoader = this.getClass().getClassLoader(); } else { classLoader = context.getClassLoader(); } Class<? extends LayoutManager> layoutManagerClass = classLoader.loadClass(className) .asSubclass(LayoutManager.class); Constructor<? extends LayoutManager> constructor; Object[] constructorArgs = null; try { constructor = layoutManagerClass.getConstructor(LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE); constructorArgs = new Object[] { context, attrs, defStyleAttr, defStyleRes }; } catch (NoSuchMethodException e) { try { constructor = layoutManagerClass.getConstructor(); } catch (NoSuchMethodException e1) { e1.initCause(e); throw new IllegalStateException( attrs.getPositionDescription() + ": Error creating LayoutManager " + className, e1); } } constructor.setAccessible(true); setLayoutManager(constructor.newInstance(constructorArgs)); } catch (ClassNotFoundException e) { throw new IllegalStateException( attrs.getPositionDescription() + ": Unable to find LayoutManager " + className, e); } catch (InvocationTargetException e) { throw new IllegalStateException(attrs.getPositionDescription() + ": Could not instantiate the LayoutManager: " + className, e); } catch (InstantiationException e) { throw new IllegalStateException(attrs.getPositionDescription() + ": Could not instantiate the LayoutManager: " + className, e); } catch (IllegalAccessException e) { throw new IllegalStateException( attrs.getPositionDescription() + ": Cannot access non-public constructor " + className, e); } catch (ClassCastException e) { throw new IllegalStateException( attrs.getPositionDescription() + ": Class is not a LayoutManager " + className, e); } } } }
From source file:ca.oson.json.Oson.java
<T> T newInstance(Map<String, Object> map, Class<T> valueType) { InstanceCreator creator = getTypeAdapter(valueType); if (creator != null) { return (T) creator.createInstance(valueType); }//from w ww . j a va2 s. c om T obj = null; if (valueType != null) { obj = (T) getDefaultValue(valueType); if (obj != null) { return obj; } } if (map == null) { return null; } // @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = As.PROPERTY, property = "@class") //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class") String JsonClassType = null; if (valueType != null) { if (getAnnotationSupport()) { for (Annotation annotation : valueType.getAnnotations()) { if (annotation instanceof JsonTypeInfo) { JsonTypeInfo jsonTypeInfo = (JsonTypeInfo) annotation; JsonTypeInfo.Id use = jsonTypeInfo.use(); JsonTypeInfo.As as = jsonTypeInfo.include(); if ((use == JsonTypeInfo.Id.MINIMAL_CLASS || use == JsonTypeInfo.Id.CLASS) && as == As.PROPERTY) { JsonClassType = jsonTypeInfo.property(); } } } } } if (JsonClassType == null) { JsonClassType = getJsonClassType(); } String className = null; if (map.containsKey(JsonClassType)) { className = map.get(JsonClassType).toString(); } Class<T> classType = getClassType(className); // && (valueType == null || valueType.isAssignableFrom(classType) || Map.class.isAssignableFrom(valueType)) if (classType != null) { valueType = classType; } if (valueType == null) { return (T) map; // or null, which is better? } Constructor<?>[] constructors = null; Class implClass = null; if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) { implClass = DeSerializerUtil.implementingClass(valueType.getName()); } if (implClass != null) { constructors = implClass.getDeclaredConstructors(); } else { constructors = valueType.getDeclaredConstructors();//.getConstructors(); } Object singleMapValue = null; Class singleMapValueType = null; if (map.size() == 1) { singleMapValue = map.get(valueType.getName()); if (singleMapValue != null) { singleMapValueType = singleMapValue.getClass(); if (singleMapValueType == String.class) { singleMapValue = StringUtil.unquote(singleMapValue.toString(), isEscapeHtml()); } try { if (valueType == Locale.class) { Constructor constructor = null; String[] parts = ((String) singleMapValue).split("_"); if (parts.length == 1) { constructor = valueType.getConstructor(String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(singleMapValue); } else if (parts.length == 2) { constructor = valueType.getConstructor(String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } else if (parts.length == 3) { constructor = valueType.getConstructor(String.class, String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } if (obj != null) { return obj; } } } catch (Exception e) { } Map<Class, Constructor> cmaps = new HashMap<>(); for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount == 1) { Class[] types = constructor.getParameterTypes(); cmaps.put(types[0], constructor); } } if (cmaps.size() > 0) { Constructor constructor = null; if ((cmaps.containsKey(Boolean.class) || cmaps.containsKey(boolean.class)) && BooleanUtil.isBoolean(singleMapValue.toString())) { constructor = cmaps.get(Boolean.class); if (constructor == null) { constructor = cmaps.get(boolean.class); } if (constructor != null) { try { constructor.setAccessible(true); obj = (T) constructor .newInstance(BooleanUtil.string2Boolean(singleMapValue.toString())); if (obj != null) { return obj; } } catch (Exception e) { } } } else if (StringUtil.isNumeric(singleMapValue.toString())) { Class[] classes = new Class[] { int.class, Integer.class, long.class, Long.class, double.class, Double.class, Byte.class, byte.class, Short.class, short.class, Float.class, float.class, BigDecimal.class, BigInteger.class, AtomicInteger.class, AtomicLong.class, Number.class }; for (Class cls : classes) { constructor = cmaps.get(cls); if (constructor != null) { try { obj = (T) constructor.newInstance(NumberUtil.getNumber(singleMapValue, cls)); if (obj != null) { return obj; } } catch (Exception e) { } } } } else if (StringUtil.isArrayOrList(singleMapValue.toString()) || singleMapValue.getClass().isArray() || Collection.class.isAssignableFrom(singleMapValue.getClass())) { for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); if (cls.isArray() || Collection.class.isAssignableFrom(cls)) { Object listObject = null; if (singleMapValue instanceof String) { JSONArray objArray = new JSONArray(singleMapValue.toString()); listObject = (List) fromJsonMap(objArray); } else { listObject = singleMapValue; } FieldData objectDTO = new FieldData(listObject, cls, true); listObject = json2Object(objectDTO); if (listObject != null) { try { obj = (T) constructor.newInstance(listObject); if (obj != null) { return obj; } } catch (Exception e) { } } } } } for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); try { obj = (T) constructor.newInstance(singleMapValue); if (obj != null) { return obj; } } catch (Exception e) { } } } } } if (implClass != null) { valueType = implClass; } try { obj = valueType.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException e) { //e.printStackTrace(); } ///* for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Annotation[] annotations = constructor.getDeclaredAnnotations(); // getAnnotations(); for (Annotation annotation : annotations) { boolean isJsonCreator = false; if (annotation instanceof JsonCreator) { isJsonCreator = true; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation; if (fieldMapper.jsonCreator() == BOOLEAN.TRUE) { isJsonCreator = true; } } if (isJsonCreator) { Parameter[] parameters = constructor.getParameters(); String[] parameterNames = ObjectUtil.getParameterNames(parameters); //parameterCount = parameters.length; Object[] parameterValues = new Object[parameterCount]; int i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameters[i].getType()); i++; } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } else { try { constructor.setAccessible(true); obj = (T) constructor.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } //*/ // try again for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); try { List<String> parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null && parameterNames.size() > 0) { Class[] parameterTypes = constructor.getParameterTypes(); int length = parameterTypes.length; if (length == parameterNames.size()) { Object[] parameterValues = new Object[length]; Object parameterValue; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } catch (IOException e1) { // e1.printStackTrace(); } } } // try more for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Class[] parameterTypes = constructor.getParameterTypes(); List<String> parameterNames; try { parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null) { int length = parameterTypes.length; if (length > parameterNames.size()) { length = parameterNames.size(); } Object[] parameterValues = new Object[length]; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | IOException e) { //e.printStackTrace(); } } } // try more try { Method[] methods = valueType.getMethods(); // .getMethod("getInstance", null); List<Method> methodList = new ArrayList<>(); if (methods != null) { for (Method method : methods) { String methodName = method.getName(); if (methodName.equals("getInstance") || methodName.equals("newInstance") || methodName.equals("createInstance") || methodName.equals("factory")) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType) && Modifier.isStatic(method.getModifiers())) { int parameterCount = method.getParameterCount(); if (parameterCount == 0) { try { obj = ObjectUtil.getMethodValue(null, method); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } else { methodList.add(method); } } } } for (Method method : methodList) { try { int parameterCount = method.getParameterCount(); Object[] parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterCount == 1 && valueType != null && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(parameterTypes[0], singleMapValueType)) { try { obj = ObjectUtil.getMethodValue(null, method, singleMapValue); if (obj != null) { return obj; } } catch (IllegalArgumentException ex) { //ex.printStackTrace(); } } } else if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } obj = ObjectUtil.getMethodValue(null, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } catch (SecurityException e) { // e.printStackTrace(); } // try all static methods, if the return type is correct, get it as the final object Method[] methods = valueType.getDeclaredMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers())) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType)) { try { Object[] parameterValues = null; int parameterCount = method.getParameterCount(); if (parameterCount > 0) { if (parameterCount == 1 && map.size() == 1 && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(method.getParameterTypes()[0], singleMapValueType)) { obj = ObjectUtil.getMethodValue(null, method, singleMapValueType); if (obj != null) { return obj; } } } parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } } obj = ObjectUtil.getMethodValue(obj, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } return null; }