List of usage examples for java.lang.reflect Constructor getParameterTypes
@Override
public Class<?>[] getParameterTypes()
From source file:org.apache.openjpa.util.ProxyManagerImpl.java
/** * Implement the methods in the {@link ProxyBean} interface. *//* w ww .ja va2s.c o m*/ private void addProxyBeanMethods(BCClass bc, Class type, Constructor cons) { // bean copy BCMethod m = bc.declareMethod("copy", Object.class, new Class[] { Object.class }); m.makePublic(); Code code = m.getCode(true); code.anew().setType(type); code.dup(); Class[] params = cons.getParameterTypes(); if (params.length == 1) { code.aload().setParam(0); code.checkcast().setType(params[0]); } code.invokespecial().setMethod(cons); if (params.length == 0) copyProperties(type, code); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); // new instance factory m = bc.declareMethod("newInstance", ProxyBean.class, new Class[] { Object.class }); m.makePublic(); code = m.getCode(true); code.anew().setType(bc); code.dup(); if (params.length == 1) { code.aload().setParam(0); code.checkcast().setType(params[0]); } code.invokespecial().setMethod("<init>", void.class, params); if (params.length == 0) copyProperties(type, code); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); }
From source file:org.apache.openjpa.util.ProxyManagerImpl.java
/** * Implement the methods in the {@link ProxyCollection} interface. *//*w w w . j a va 2s .c om*/ private void addProxyCollectionMethods(BCClass bc, Class type) { // change tracker BCField changeTracker = bc.declareField("changeTracker", CollectionChangeTracker.class); changeTracker.setTransient(true); BCMethod m = bc.declareMethod("getChangeTracker", ChangeTracker.class, null); m.makePublic(); Code code = m.getCode(true); code.aload().setThis(); code.getfield().setField(changeTracker); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); // collection copy Constructor cons = findCopyConstructor(type); if (cons == null && SortedSet.class.isAssignableFrom(type)) cons = findComparatorConstructor(type); Class[] params = (cons == null) ? new Class[0] : cons.getParameterTypes(); m = bc.declareMethod("copy", Object.class, new Class[] { Object.class }); m.makePublic(); code = m.getCode(true); code.anew().setType(type); code.dup(); if (params.length == 1) { code.aload().setParam(0); if (params[0] == Comparator.class) { code.checkcast().setType(SortedSet.class); code.invokeinterface().setMethod(SortedSet.class, "comparator", Comparator.class, null); } else code.checkcast().setType(params[0]); } code.invokespecial().setMethod(type, "<init>", void.class, params); if (params.length == 0 || params[0] == Comparator.class) { code.dup(); code.aload().setParam(0); code.checkcast().setType(Collection.class); code.invokevirtual().setMethod(type, "addAll", boolean.class, new Class[] { Collection.class }); code.pop(); } code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); // element type BCField elementType = bc.declareField("elementType", Class.class); elementType.setTransient(true); m = bc.declareMethod("getElementType", Class.class, null); m.makePublic(); code = m.getCode(true); code.aload().setThis(); code.getfield().setField(elementType); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); // new instance factory m = bc.declareMethod("newInstance", ProxyCollection.class, new Class[] { Class.class, Comparator.class, boolean.class, boolean.class }); m.makePublic(); code = m.getCode(true); code.anew().setType(bc); code.dup(); cons = findComparatorConstructor(type); params = (cons == null) ? new Class[0] : cons.getParameterTypes(); if (params.length == 1) code.aload().setParam(1); code.invokespecial().setMethod("<init>", void.class, params); int ret = code.getNextLocalsIndex(); code.astore().setLocal(ret); // set element type code.aload().setLocal(ret); code.aload().setParam(0); code.putfield().setField(elementType); // create change tracker and set it code.iload().setParam(2); JumpInstruction ifins = code.ifeq(); code.aload().setLocal(ret); code.anew().setType(CollectionChangeTrackerImpl.class); code.dup(); code.aload().setLocal(ret); code.constant().setValue(allowsDuplicates(type)); code.constant().setValue(isOrdered(type)); code.aload().setParam(3); code.invokespecial().setMethod(CollectionChangeTrackerImpl.class, "<init>", void.class, new Class[] { Collection.class, boolean.class, boolean.class, boolean.class }); code.putfield().setField(changeTracker); ifins.setTarget(code.aload().setLocal(ret)); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); }
From source file:org.apache.openjpa.util.ProxyManagerImpl.java
/** * Implement the methods in the {@link ProxyMap} interface. */// ww w.j a va 2s. co m private void addProxyMapMethods(BCClass bc, Class type) { // change tracker BCField changeTracker = bc.declareField("changeTracker", MapChangeTracker.class); changeTracker.setTransient(true); BCMethod m = bc.declareMethod("getChangeTracker", ChangeTracker.class, null); m.makePublic(); Code code = m.getCode(true); code.aload().setThis(); code.getfield().setField(changeTracker); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); // map copy Constructor cons = findCopyConstructor(type); if (cons == null && SortedMap.class.isAssignableFrom(type)) cons = findComparatorConstructor(type); Class[] params = (cons == null) ? new Class[0] : cons.getParameterTypes(); m = bc.declareMethod("copy", Object.class, new Class[] { Object.class }); m.makePublic(); code = m.getCode(true); code.anew().setType(type); code.dup(); if (params.length == 1) { code.aload().setParam(0); if (params[0] == Comparator.class) { code.checkcast().setType(SortedMap.class); code.invokeinterface().setMethod(SortedMap.class, "comparator", Comparator.class, null); } else code.checkcast().setType(params[0]); } code.invokespecial().setMethod(type, "<init>", void.class, params); if (params.length == 0 || params[0] == Comparator.class) { code.dup(); code.aload().setParam(0); code.checkcast().setType(Map.class); code.invokevirtual().setMethod(type, "putAll", void.class, new Class[] { Map.class }); } code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); // key type BCField keyType = bc.declareField("keyType", Class.class); keyType.setTransient(true); m = bc.declareMethod("getKeyType", Class.class, null); m.makePublic(); code = m.getCode(true); code.aload().setThis(); code.getfield().setField(keyType); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); // value type BCField valueType = bc.declareField("valueType", Class.class); valueType.setTransient(true); m = bc.declareMethod("getValueType", Class.class, null); m.makePublic(); code = m.getCode(true); code.aload().setThis(); code.getfield().setField(valueType); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); // new instance factory m = bc.declareMethod("newInstance", ProxyMap.class, new Class[] { Class.class, Class.class, Comparator.class, boolean.class, boolean.class }); m.makePublic(); code = m.getCode(true); code.anew().setType(bc); code.dup(); cons = findComparatorConstructor(type); params = (cons == null) ? new Class[0] : cons.getParameterTypes(); if (params.length == 1) code.aload().setParam(2); code.invokespecial().setMethod("<init>", void.class, params); int ret = code.getNextLocalsIndex(); code.astore().setLocal(ret); // set key and value types code.aload().setLocal(ret); code.aload().setParam(0); code.putfield().setField(keyType); code.aload().setLocal(ret); code.aload().setParam(1); code.putfield().setField(valueType); // create change tracker and set it code.iload().setParam(3); JumpInstruction ifins = code.ifeq(); code.aload().setLocal(ret); code.anew().setType(MapChangeTrackerImpl.class); code.dup(); code.aload().setLocal(ret); code.aload().setParam(4); code.invokespecial().setMethod(MapChangeTrackerImpl.class, "<init>", void.class, new Class[] { Map.class, boolean.class }); code.putfield().setField(changeTracker); ifins.setTarget(code.aload().setLocal(ret)); code.areturn(); code.calculateMaxStack(); code.calculateMaxLocals(); }
From source file:org.dasein.persist.PersistentCache.java
@SuppressWarnings({ "rawtypes", "unchecked" }) protected Object mapValue(String fieldName, Object dataStoreValue, Class<?> toType, ParameterizedType ptype) throws PersistenceException { LookupDelegate delegate = getLookupDelegate(fieldName); if (dataStoreValue != null && delegate != null && !delegate.validate(dataStoreValue.toString())) { throw new PersistenceException("Value " + dataStoreValue + " for " + fieldName + " is not valid."); }/*w w w . j av a 2 s. co m*/ try { if (toType.equals(String.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof String)) { dataStoreValue = dataStoreValue.toString(); } } else if (Enum.class.isAssignableFrom(toType)) { if (dataStoreValue != null) { Enum e = Enum.valueOf((Class<? extends Enum>) toType, dataStoreValue.toString()); dataStoreValue = e; } } else if (toType.equals(Boolean.class) || toType.equals(boolean.class)) { if (dataStoreValue == null) { dataStoreValue = false; } else if (!(dataStoreValue instanceof Boolean)) { if (Number.class.isAssignableFrom(dataStoreValue.getClass())) { dataStoreValue = (((Number) dataStoreValue).intValue() != 0); } else { dataStoreValue = (dataStoreValue.toString().trim().equalsIgnoreCase("true") || dataStoreValue.toString().trim().equalsIgnoreCase("y")); } } } else if (Number.class.isAssignableFrom(toType) || toType.equals(byte.class) || toType.equals(short.class) || toType.equals(long.class) || toType.equals(int.class) || toType.equals(float.class) || toType.equals(double.class)) { if (dataStoreValue == null) { if (toType.equals(int.class) || toType.equals(short.class) || toType.equals(long.class)) { dataStoreValue = 0; } else if (toType.equals(float.class) || toType.equals(double.class)) { dataStoreValue = 0.0f; } } else if (toType.equals(Number.class)) { if (!(dataStoreValue instanceof Number)) { if (dataStoreValue instanceof String) { try { dataStoreValue = Double.parseDouble((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException("Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } } else if (toType.equals(Integer.class) || toType.equals(int.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Integer)) { dataStoreValue = ((Number) dataStoreValue).intValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Integer.parseInt((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Long.class) || toType.equals(long.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Long)) { dataStoreValue = ((Number) dataStoreValue).longValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Long.parseLong((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1L : 0L); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Byte.class) || toType.equals(byte.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Byte)) { dataStoreValue = ((Number) dataStoreValue).byteValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Byte.parseByte((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Short.class) || toType.equals(short.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Short)) { dataStoreValue = ((Number) dataStoreValue).shortValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Short.parseShort((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Double.class) || toType.equals(double.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Double)) { dataStoreValue = ((Number) dataStoreValue).doubleValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Double.parseDouble((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1.0 : 0.0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Float.class) || toType.equals(float.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Float)) { dataStoreValue = ((Number) dataStoreValue).floatValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Float.parseFloat((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1.0f : 0.0f); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(BigDecimal.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof BigDecimal)) { if (dataStoreValue instanceof BigInteger) { dataStoreValue = new BigDecimal((BigInteger) dataStoreValue); } else { dataStoreValue = BigDecimal.valueOf(((Number) dataStoreValue).doubleValue()); } } } else if (dataStoreValue instanceof String) { try { dataStoreValue = new BigDecimal((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0)); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(BigInteger.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof BigInteger)) { if (dataStoreValue instanceof BigDecimal) { dataStoreValue = ((BigDecimal) dataStoreValue).toBigInteger(); } else { dataStoreValue = BigInteger.valueOf(((Number) dataStoreValue).longValue()); } } } else if (dataStoreValue instanceof String) { try { dataStoreValue = new BigDecimal((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0)); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue != null) { logger.error("Type of dataStoreValue=" + dataStoreValue.getClass()); throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Locale.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof Locale)) { String[] parts = dataStoreValue.toString().split("_"); if (parts != null && parts.length > 1) { dataStoreValue = new Locale(parts[0], parts[1]); } else { dataStoreValue = new Locale(parts[0]); } } } else if (Measured.class.isAssignableFrom(toType)) { if (dataStoreValue != null && ptype != null) { if (Number.class.isAssignableFrom(dataStoreValue.getClass())) { Constructor<? extends Measured> constructor = null; double value = ((Number) dataStoreValue).doubleValue(); for (Constructor<?> c : toType.getDeclaredConstructors()) { Class[] args = c.getParameterTypes(); if (args != null && args.length == 2 && Number.class.isAssignableFrom(args[0]) && UnitOfMeasure.class.isAssignableFrom(args[1])) { constructor = (Constructor<? extends Measured>) c; break; } } if (constructor == null) { throw new PersistenceException("Unable to map with no proper constructor"); } dataStoreValue = constructor.newInstance(value, ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance()); } else if (!(dataStoreValue instanceof Measured)) { try { dataStoreValue = Double.parseDouble(dataStoreValue.toString()); } catch (NumberFormatException e) { Method method = null; for (Method m : toType.getDeclaredMethods()) { if (Modifier.isStatic(m.getModifiers()) && m.getName().equals("valueOf")) { if (m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(String.class)) { method = m; break; } } } if (method == null) { throw new PersistenceException("Don't know how to map " + dataStoreValue + " to " + toType + "<" + ptype + ">"); } dataStoreValue = method.invoke(null, dataStoreValue.toString()); } } // just because we converted it to a measured object above doesn't mean // we have the unit of measure right if (dataStoreValue instanceof Measured) { UnitOfMeasure targetUom = (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]) .newInstance(); if (!(((Measured) dataStoreValue).getUnitOfMeasure()).equals(targetUom)) { dataStoreValue = ((Measured) dataStoreValue).convertTo( (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance()); } } } } else if (toType.equals(UUID.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof UUID)) { dataStoreValue = UUID.fromString(dataStoreValue.toString()); } } else if (toType.equals(TimeZone.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof TimeZone)) { dataStoreValue = TimeZone.getTimeZone(dataStoreValue.toString()); } } else if (toType.equals(Currency.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof Currency)) { dataStoreValue = Currency.getInstance(dataStoreValue.toString()); } } else if (toType.isArray()) { Class<?> t = toType.getComponentType(); if (dataStoreValue == null) { dataStoreValue = Array.newInstance(t, 0); } else if (dataStoreValue instanceof JSONArray) { JSONArray arr = (JSONArray) dataStoreValue; if (long.class.isAssignableFrom(t)) { long[] replacement = (long[]) Array.newInstance(long.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Long) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else if (int.class.isAssignableFrom(t)) { int[] replacement = (int[]) Array.newInstance(int.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Integer) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else if (float.class.isAssignableFrom(t)) { float[] replacement = (float[]) Array.newInstance(float.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Float) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else if (double.class.isAssignableFrom(t)) { double[] replacement = (double[]) Array.newInstance(double.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Double) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else if (boolean.class.isAssignableFrom(t)) { boolean[] replacement = (boolean[]) Array.newInstance(boolean.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Boolean) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else { Object[] replacement = (Object[]) Array.newInstance(t, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } } else if (!dataStoreValue.getClass().isArray()) { logger.error("Unable to map data store type " + dataStoreValue.getClass().getName() + " to " + toType.getName()); logger.error("Value of " + fieldName + "=" + dataStoreValue); throw new PersistenceException("Data store type=" + dataStoreValue.getClass().getName()); } } else if (dataStoreValue != null && !toType.isAssignableFrom(dataStoreValue.getClass())) { Annotation[] alist = toType.getDeclaredAnnotations(); boolean autoJSON = false; for (Annotation a : alist) { if (a instanceof AutoJSON) { autoJSON = true; } } if (autoJSON) { dataStoreValue = autoDeJSON(toType, (JSONObject) dataStoreValue); } else { try { Method m = toType.getDeclaredMethod("valueOf", JSONObject.class); dataStoreValue = m.invoke(null, dataStoreValue); } catch (NoSuchMethodException ignore) { try { Method m = toType.getDeclaredMethod("valueOf", String.class); if (m != null) { dataStoreValue = m.invoke(null, dataStoreValue.toString()); } else { throw new PersistenceException( "No valueOf() field in " + toType + " for mapping " + fieldName); } } catch (NoSuchMethodException e) { throw new PersistenceException("No valueOf() field in " + toType + " for mapping " + fieldName + " with " + dataStoreValue + ": (" + dataStoreValue.getClass().getName() + " vs " + toType.getName() + ")"); } } } } } catch (Exception e) { String err = "Error mapping field in " + toType + " for " + fieldName + ": " + e.getMessage(); logger.error(err, e); throw new PersistenceException(); } return dataStoreValue; }
From source file:org.apache.accumulo.test.ShellServerIT.java
License:asdf
private DistCp newDistCp(Configuration conf) { try {// www. j a va2 s . c o m @SuppressWarnings("unchecked") Constructor<DistCp>[] constructors = (Constructor<DistCp>[]) DistCp.class.getConstructors(); for (Constructor<DistCp> constructor : constructors) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length > 0 && parameterTypes[0].equals(Configuration.class)) { if (parameterTypes.length == 1) { return constructor.newInstance(conf); } else if (parameterTypes.length == 2) { return constructor.newInstance(conf, null); } } } } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("Unexpected constructors for DistCp"); }
From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java
/** * Test for {@link ReflectionUtils#getShortestConstructor(Class)}. *//*w w w. j a v a 2 s .c om*/ public void test_getShortestConstructor() throws Exception { Class<Class_getShortestConstructor> clazz = Class_getShortestConstructor.class; // check that longer constructor is before shorter { Constructor<?>[] constructors = clazz.getDeclaredConstructors(); assertThat(constructors[0].getParameterTypes()).hasSize(2); assertThat(constructors[1].getParameterTypes()).hasSize(1); } // do test { Constructor<?> constructor = ReflectionUtils.getShortestConstructor(clazz); assertThat(constructor.getParameterTypes()).hasSize(1); } }
From source file:org.accada.reader.rprm.core.ReaderDevice.java
/** * Reads the configuration of the io triggers from property file. * @param conf/* w w w . j ava2 s . co m*/ * The configuration * @throws ReaderProtocolException * "wrong edgeTrigger in property file" */ private void getIoTriggers(final XMLConfiguration conf) throws ReaderProtocolException { // get io value triggers SubnodeConfiguration valueTriggerConf = conf.configurationAt("IOValueTriggerPortManager"); String port; for (int i = 0; i <= valueTriggerConf.getMaxIndex("port"); i++) { port = valueTriggerConf.getString("port(" + i + ")"); try { Class cls = Class.forName(valueTriggerConf.getString(port)); Class[] partypes = new Class[] {}; Constructor ct = cls.getConstructor(partypes); Class[] cl = ct.getParameterTypes(); Object[] arglist = new Object[] {}; IOValueTriggerPortManager manager = (IOValueTriggerPortManager) ct.newInstance(arglist); final int num = 4; valueTriggers.put(port.substring(num), manager); } catch (Exception e) { throw new ReaderProtocolException("wrong valueTrigger in property file", MessagingConstants.ERROR_UNKNOWN); } } // get io edge triggers SubnodeConfiguration edgeTriggerConf = conf.configurationAt("IOEdgeTriggerPortManager"); for (int i = 0; i <= valueTriggerConf.getMaxIndex("port"); i++) { port = edgeTriggerConf.getString("port(" + i + ")"); try { Class cls = Class.forName(edgeTriggerConf.getString(port)); Class[] partypes = new Class[] {}; Constructor ct = cls.getConstructor(partypes); Class[] cl = ct.getParameterTypes(); Object[] arglist = new Object[] {}; IOEdgeTriggerPortManager manager = (IOEdgeTriggerPortManager) ct.newInstance(arglist); final int num = 4; edgeTriggers.put(port.substring(num), manager); } catch (Exception e) { throw new ReaderProtocolException("wrong edgeTrigger in property file", MessagingConstants.ERROR_UNKNOWN); } } }
From source file:org.apache.solr.core.SolrCore.java
/** * Creates an instance by trying a constructor that accepts a SolrCore before * trying the default (no arg) constructor. * * @param className the instance class to create * @param cast the class or interface that the instance should extend or implement * @param msg a message helping compose the exception error if any occurs. * @param core The SolrCore instance for which this object needs to be loaded * @return the desired instance/*from w ww. j a v a 2s .c o m*/ * @throws SolrException if the object could not be instantiated */ public static <T> T createInstance(String className, Class<T> cast, String msg, SolrCore core, ResourceLoader resourceLoader) { Class<? extends T> clazz = null; if (msg == null) msg = "SolrCore Object"; try { clazz = resourceLoader.findClass(className, cast); //most of the classes do not have constructors which takes SolrCore argument. It is recommended to obtain SolrCore by implementing SolrCoreAware. // So invariably always it will cause a NoSuchMethodException. So iterate though the list of available constructors Constructor<?>[] cons = clazz.getConstructors(); for (Constructor<?> con : cons) { Class<?>[] types = con.getParameterTypes(); if (types.length == 1 && types[0] == SolrCore.class) { return cast.cast(con.newInstance(core)); } } return resourceLoader.newInstance(className, cast);//use the empty constructor } catch (SolrException e) { throw e; } catch (Exception e) { // The JVM likes to wrap our helpful SolrExceptions in things like // "InvocationTargetException" that have no useful getMessage if (null != e.getCause() && e.getCause() instanceof SolrException) { SolrException inner = (SolrException) e.getCause(); throw inner; } throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error Instantiating " + msg + ", " + className + " failed to instantiate " + cast.getName(), e); } }
From source file:io.milton.config.HttpManagerBuilder.java
private Object createObject(Class c) throws CreationException { log.info("createObject: {}", c.getCanonicalName()); // Look for an @Inject or default constructor Constructor found = null; for (Constructor con : c.getConstructors()) { Annotation[][] paramTypes = con.getParameterAnnotations(); if (paramTypes != null && paramTypes.length > 0) { Annotation inject = con.getAnnotation(Inject.class); if (inject != null) { found = con;// w w w.ja va2 s . c o m } } else { found = con; } } if (found == null) { throw new RuntimeException( "Could not find a default or @Inject constructor for class: " + c.getCanonicalName()); } Object args[] = new Object[found.getParameterTypes().length]; int i = 0; for (Class paramType : found.getParameterTypes()) { try { args[i++] = findOrCreateObject(paramType); } catch (CreationException ex) { throw new CreationException(c, ex); } } Object created; try { log.info("Creating: {}", c.getCanonicalName()); created = found.newInstance(args); rootContext.put(created); } catch (InstantiationException ex) { throw new CreationException(c, ex); } catch (IllegalAccessException ex) { throw new CreationException(c, ex); } catch (IllegalArgumentException ex) { throw new CreationException(c, ex); } catch (InvocationTargetException ex) { throw new CreationException(c, ex); } // Now look for @Inject fields for (Field field : c.getDeclaredFields()) { Inject anno = field.getAnnotation(Inject.class); if (anno != null) { boolean acc = field.isAccessible(); try { field.setAccessible(true); field.set(created, findOrCreateObject(field.getType())); } catch (IllegalArgumentException ex) { throw new CreationException(field, c, ex); } catch (IllegalAccessException ex) { throw new CreationException(field, c, ex); } finally { field.setAccessible(acc); // put back the way it was } } } // Finally set any @Inject methods for (Method m : c.getMethods()) { Inject anno = m.getAnnotation(Inject.class); if (anno != null) { Object[] methodArgs = new Object[m.getParameterTypes().length]; int ii = 0; try { for (Class<?> paramType : m.getParameterTypes()) { methodArgs[ii++] = findOrCreateObject(paramType); } m.invoke(created, methodArgs); } catch (CreationException creationException) { throw new CreationException(m, c, creationException); } catch (IllegalAccessException ex) { throw new CreationException(m, c, ex); } catch (IllegalArgumentException ex) { throw new CreationException(m, c, ex); } catch (InvocationTargetException ex) { throw new CreationException(m, c, ex); } } } if (created instanceof InitListener) { if (listeners == null) { listeners = new ArrayList<InitListener>(); } InitListener l = (InitListener) created; l.beforeInit(this); // better late then never!! listeners.add(l); } return created; }