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:android.support.transition.TransitionInflater.java
private Object createCustom(AttributeSet attrs, Class expectedType, String tag) { String className = attrs.getAttributeValue(null, "class"); if (className == null) { throw new InflateException(tag + " tag must have a 'class' attribute"); }//from www.jav a 2 s . c om try { synchronized (CONSTRUCTORS) { Constructor constructor = CONSTRUCTORS.get(className); if (constructor == null) { @SuppressWarnings("unchecked") Class<?> c = mContext.getClassLoader().loadClass(className).asSubclass(expectedType); if (c != null) { constructor = c.getConstructor(CONSTRUCTOR_SIGNATURE); constructor.setAccessible(true); CONSTRUCTORS.put(className, constructor); } } //noinspection ConstantConditions return constructor.newInstance(mContext, attrs); } } catch (Exception e) { throw new InflateException("Could not instantiate " + expectedType + " class " + className, e); } }
From source file:org.zanata.seam.SeamAutowire.java
/** * Creates (but does not autowire) the bean instance for the provided * class./*from www. j a v a2 s . c om*/ * * @param fieldClass * The bean class to create - may be an interface if useImpl * was called, otherwise must have a no-arg constructor per Seam * spec. * @return The bean. */ private <T> T create(Class<T> fieldClass, String beanPath) { // field might be an interface, but we need to find the // implementation class Class<T> beanClass = getImplClass(fieldClass); // The bean class might be an interface if (beanClass.isInterface()) { throw new AutowireException("" + "Could not auto-wire bean with path " + beanPath + " of type " + beanClass.getName() + ". The bean is defined as an interface, but no " + "implementations have been defined for it."); } try { // No-arg constructor Constructor<T> constructor = beanClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (NoSuchMethodException e) { throw new AutowireException("" + "Could not auto-wire bean with path " + beanPath + " of type " + beanClass.getName() + ". No no-args constructor.", e); } catch (InvocationTargetException e) { throw new AutowireException("" + "Could not auto-wire bean with path " + beanPath + " of type " + beanClass.getName() + ". Exception thrown from constructor.", e); } catch (Exception e) { throw new AutowireException( "" + "Could not auto-wire bean with path " + beanPath + " of type " + beanClass.getName(), e); } }
From source file:com.sixt.service.framework.registry.consul.RegistrationManager.java
protected String getProtobufClassFieldDescriptions(Class<? extends Message> messageClass) throws Exception { StringBuilder sb = new StringBuilder(); Constructor<?> constructor = null; try {// w ww.ja v a 2 s . c o m constructor = messageClass.getDeclaredConstructor(); } catch (NoSuchMethodException nsmex) { //Issue #35 logger.info("Unsupported protobuf field: {}", messageClass.getName()); return sb.toString(); } constructor.setAccessible(true); Object instance = constructor.newInstance(); Message.Builder builder = ((Message) instance).newBuilderForType(); Message message = builder.build(); Descriptors.Descriptor requestDesc = message.getDescriptorForType(); List<Descriptors.FieldDescriptor> requestFields = requestDesc.getFields(); Iterator<Descriptors.FieldDescriptor> iter = requestFields.iterator(); while (iter.hasNext()) { Descriptors.FieldDescriptor fd = iter.next(); //TODO: deal with repeated fields sb.append("{\"name\":\""); sb.append(fd.getName()); sb.append("\",\"type\":\""); if (fd.getType().toString().equalsIgnoreCase("message")) { sb.append(getLastComponent(fd.getMessageType().getFullName())); sb.append("\",\"values\":["); Descriptors.FieldDescriptor childDescriptor = requestDesc.findFieldByName(fd.getName()); Message.Builder subMessageBuilder = builder.newBuilderForField(childDescriptor); Message subMessage = subMessageBuilder.build(); sb.append(getProtobufClassFieldDescriptions(subMessage.getClass())); sb.append("]}"); } else { sb.append(fd.getType().toString().toLowerCase()); sb.append("\",\"values\":null}"); } if (iter.hasNext()) { sb.append(","); } } return sb.toString(); }
From source file:org.thaliproject.p2p.btconnectorlib.internal.bluetooth.BluetoothUtils.java
/** * Creates a new Bluetooth socket with the given service record UUID and the given channel/port. * @param bluetoothDevice The Bluetooth device. * @param serviceRecordUuid The service record UUID. * @param channelOrPort The RFCOMM channel or L2CAP psm to use. * @param secure If true, will try to create a secure RFCOMM socket. If false, will try to create an insecure one. * @return A new Bluetooth socket with the specified channel/port or null in case of a failure. *//*from w w w . ja v a2 s .co m*/ public static BluetoothSocket createBluetoothSocketToServiceRecord(BluetoothDevice bluetoothDevice, UUID serviceRecordUuid, int channelOrPort, boolean secure) { Constructor[] bluetoothSocketConstructors = BluetoothSocket.class.getDeclaredConstructors(); Constructor bluetoothSocketConstructor = null; for (Constructor constructor : bluetoothSocketConstructors) { Class<?>[] parameterTypes = constructor.getParameterTypes(); boolean takesBluetoothDevice = false; boolean takesParcelUuid = false; for (Class<?> parameterType : parameterTypes) { if (parameterType.equals(BluetoothDevice.class)) { takesBluetoothDevice = true; } else if (parameterType.equals(ParcelUuid.class)) { takesParcelUuid = true; } } if (takesBluetoothDevice && takesParcelUuid) { // We found the right constructor bluetoothSocketConstructor = constructor; break; } } // This is the constructor we should now have: // BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, BluetoothDevice device, // int port, ParcelUuid uuid) throws IOException // Create the parameters for the constructor Object[] parameters = new Object[] { Integer.valueOf(1), // BluetoothSocket.TYPE_RFCOMM Integer.valueOf(-1), Boolean.valueOf(secure), Boolean.valueOf(secure), bluetoothDevice, Integer.valueOf(channelOrPort), new ParcelUuid(serviceRecordUuid) }; bluetoothSocketConstructor.setAccessible(true); BluetoothSocket bluetoothSocket = null; try { bluetoothSocket = (BluetoothSocket) bluetoothSocketConstructor.newInstance(parameters); Log.d(TAG, "createBluetoothSocketToServiceRecord: Socket created with channel/port " + channelOrPort); } catch (Exception e) { Log.e(TAG, "createBluetoothSocketToServiceRecord: Failed to create a new Bluetooth socket instance: " + e.getMessage(), e); } return bluetoothSocket; }
From source file:hu.bme.mit.sette.common.model.snippet.SnippetInputFactoryContainer.java
/** * Validates the constructor of the class. * * @param validator/*w ww .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:eu.europa.esig.dss.validation.SignedDocumentValidator.java
/** * This method guesses the document format and returns an appropriate document validator. * * @param dssDocument/* w w w. j av a 2s . c om*/ * The instance of {@code DSSDocument} to validate * @return returns the specific instance of SignedDocumentValidator in terms of the document type */ public static SignedDocumentValidator fromDocument(final DSSDocument dssDocument) { if (CollectionUtils.isEmpty(registredDocumentValidators)) { throw new DSSException("No validator registred"); } for (Class<SignedDocumentValidator> clazz : registredDocumentValidators) { try { Constructor<SignedDocumentValidator> defaultAndPrivateConstructor = clazz.getDeclaredConstructor(); defaultAndPrivateConstructor.setAccessible(true); SignedDocumentValidator validator = defaultAndPrivateConstructor.newInstance(); if (validator.isSupported(dssDocument)) { Constructor<? extends SignedDocumentValidator> constructor = clazz .getDeclaredConstructor(DSSDocument.class); return constructor.newInstance(dssDocument); } } catch (Exception e) { LOG.error("Cannot instanciate class '" + clazz.getName() + "' : " + e.getMessage(), e); } } throw new DSSException("Document format not recognized/handled"); }
From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java
/** * @param signature//from w ww . j av a2 s . c o m * the signature of {@link Constructor} 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) { 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:com.transitionseverywhere.TransitionInflater.java
private Object createCustom(AttributeSet attrs, Class expectedType, String tag) { String className = attrs.getAttributeValue(null, "class"); if (className == null) { throw new InflateException(tag + " tag must have a 'class' attribute"); }//w w w . j a va2s . co m try { synchronized (sConstructors) { Constructor constructor = sConstructors.get(className); if (constructor == null) { Class c = mContext.getClassLoader().loadClass(className).asSubclass(expectedType); if (c != null) { constructor = c.getConstructor(sConstructorSignature); if (!constructor.isAccessible()) { constructor.setAccessible(true); } sConstructors.put(className, constructor); } } return constructor.newInstance(mContext, attrs); } } catch (InstantiationException e) { throw new InflateException("Could not instantiate " + expectedType + " class " + className, e); } catch (ClassNotFoundException e) { throw new InflateException("Could not instantiate " + expectedType + " class " + className, e); } catch (InvocationTargetException e) { throw new InflateException("Could not instantiate " + expectedType + " class " + className, e); } catch (NoSuchMethodException e) { throw new InflateException("Could not instantiate " + expectedType + " class " + className, e); } catch (IllegalAccessException e) { throw new InflateException("Could not instantiate " + expectedType + " class " + className, e); } }
From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java
/** * @param signature/*from w w w.j a v a 2 s . co m*/ * the generic signature of {@link Constructor} in same format as * {@link #getConstructorGenericSignature(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> getConstructorByGenericSignature(Class<T> clazz, String signature) { Assert.isNotNull(clazz); Assert.isNotNull(signature); // check all declared constructors for (Constructor<?> constructor : clazz.getDeclaredConstructors()) { if (getConstructorGenericSignature(constructor).equals(signature)) { constructor.setAccessible(true); return (Constructor<T>) constructor; } } // not found return null; }
From source file:org.leo.benchmark.Benchmark.java
/** * Execute the current run code loop times. * // w w w .j av a 2s . c o m * @param run code to run * @param loop number of time to run the code * @param taskName name displayed at the end of the task */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void execute(BenchRunnable run, int loop, String taskName) { System.out.print(taskName + " ... "); // set default context collection.clear(); collection.addAll(defaultCtx); // warmup warmUp(); isTimeout = false; // timeout timer Timer timer = new Timer((int) timeout, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { isTimeout = true; // to raise a ConcurrentModificationException or a // NoSuchElementException to interrupt internal work in the List collection.clear(); } }); timer.setRepeats(false); timer.start(); long startTime = System.nanoTime(); int i; for (i = 0; i < loop && !isTimeout; i++) { try { run.run(i); } catch (Exception e) { // on purpose so ignore it } } timer.stop(); long time = isTimeout ? timeout * 1000000 : System.nanoTime() - startTime; System.out.println((isTimeout ? "Timeout (>" + time + "ns) after " + i + " loop(s)" : time + "ns")); // restore default context, // the collection instance might have been // corrupted by the timeout so create a new instance try { Constructor<? extends Collection> constructor = collection.getClass() .getDeclaredConstructor((Class<?>[]) null); constructor.setAccessible(true); collection = constructor.newInstance(); // update the reference if (collection instanceof List) { list = (List<String>) collection; } } catch (Exception e1) { e1.printStackTrace(); } // store the results for display Map<Class<? extends Collection<?>>, Long> currentBench = benchResults.get(taskName); if (currentBench == null) { currentBench = new HashMap<Class<? extends Collection<?>>, Long>(); benchResults.put(taskName, currentBench); } currentBench.put((Class<? extends Collection<String>>) collection.getClass(), time); // little gc to clean up all the stuff System.gc(); }