List of usage examples for java.lang Class getConstructors
@CallerSensitive public Constructor<?>[] getConstructors() throws SecurityException
From source file:org.apache.axis2.wsdl.codegen.emitter.AxisServiceBasedMultiLanguageEmitter.java
private void addConstructorDetails(Document doc, Element faultElement, String exceptionClassName) throws ClassNotFoundException { Class exceptionClass = Class.forName(exceptionClassName); Constructor[] constructors = exceptionClass.getConstructors(); for (int i = 0; i < constructors.length; i++) { Element constructorElement = doc.createElement("constructor"); faultElement.appendChild(constructorElement); Type[] parameters = constructors[i].getGenericParameterTypes(); List existingParamNames = new ArrayList(); for (int j = 0; j < parameters.length; j++) { Element parameterElement = doc.createElement("param"); constructorElement.appendChild(parameterElement); addAttribute(doc, "type", getTypeName(parameters[j]), parameterElement); addAttribute(doc, "name", getParameterName(parameters[j], existingParamNames), parameterElement); }/*from w ww . j a va 2s . c o m*/ } }
From source file:org.apache.solr.core.SolrCore.java
private UpdateHandler createReloadedUpdateHandler(String className, String msg, UpdateHandler updateHandler) { Class<? extends UpdateHandler> clazz = null; if (msg == null) msg = "SolrCore Object"; try {/*w w w .java 2s .c o m*/ clazz = getResourceLoader().findClass(className, UpdateHandler.class); //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 == 2 && types[0] == SolrCore.class && types[1] == UpdateHandler.class) { return UpdateHandler.class.cast(con.newInstance(this, updateHandler)); } } throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error Instantiating " + msg + ", " + className + " could not find proper constructor for " + UpdateHandler.class.getName()); } 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 " + UpdateHandler.class.getName(), e); } }
From source file:edu.ku.brc.ui.UIRegistry.java
/** * @param actionClass/*from ww w. ja va 2 s.co m*/ * @param owner * @param name * @param icon * @param toolTip * @param mnemonicKeyCode * @param acceleratorKey * @return */ public Action makeAction(Class<?> actionClass, Object owner, String name, ImageIcon icon, String toolTip, Integer mnemonicKeyCode, KeyStroke acceleratorKey) { Action a = null; try { Constructor<?> c; if (owner != null) { // If the class is an inner class, its constuctor takes a hidden // parameter, an object of it enclosing class. c = actionClass.getConstructor(new Class<?>[] { owner.getClass() }); a = (Action) c.newInstance(new Object[] { owner }); } else { c = actionClass.getConstructor((Class<?>[]) null); a = (Action) c.newInstance((Object[]) null); } return makeAction(a, name, icon, toolTip, mnemonicKeyCode, acceleratorKey); } catch (ClassCastException e) { System.err.println("actionClass argument " + actionClass + " does not implement Action"); } catch (Exception e) { System.err.println(e + " -- while trying to make an instance of " + actionClass); try { // Output a list of constructors available for this class. Constructor<?>[] cc = actionClass.getConstructors(); for (int i = 0; i < cc.length; i++) { System.err.println(cc[i].toString()); } } catch (Exception ee) { log.error(ee); } } return a; }
From source file:org.regenstrief.util.Util.java
/** * Writes information about a .jar/*from ww w. j a v a2s . c o m*/ * * @param path the path of the .jar * @param w the Writer * @throws Exception if an I/O problem occurs **/ public final static void jarInfo(final String path, final Writer w) throws Exception { final JarFile jar = new JarFile(new File(path)); final Enumeration<JarEntry> en = jar.entries(); final PrintWriter pw = getPrintWriter(w); while (en.hasMoreElements()) { final String name = en.nextElement().getName(); if (!name.endsWith(".class")) { continue; } try { Class<?> c = Class.forName(name.substring(0, name.length() - 6).replace('/', '.')); final Member[][] allMembers = new Member[][] { c.getFields(), c.getConstructors(), c.getMethods() }; pw.print(c); for (c = c.getSuperclass(); c != null; c = c.getSuperclass()) { pw.print(" extends "); pw.print(c.getName()); } pw.println(); pw.println('{'); for (int j = 0; j < allMembers.length; j++) { final Member[] members = allMembers[j]; for (final Member member : members) { if (!Modifier.isPublic(member.getModifiers())) { continue; } pw.print('\t'); pw.print(member); pw.println(';'); } if ((members.length > 0) && (j < allMembers.length - 1)) { pw.println(); } } pw.println('}'); } catch (final Throwable e) { pw.println(e); } pw.println(); } pw.flush(); jar.close(); }
From source file:org.gradle.api.internal.AbstractClassGenerator.java
private <T> Class<? extends T> generateUnderLock(Class<T> type) { Map<Class<?>, Class<?>> cache = GENERATED_CLASSES.get(getClass()); if (cache == null) { // WeakHashMap won't work here. It keeps a strong reference to the mapping value, which is the generated class in this case // However, the generated class has a strong reference to the source class (by extending it), so the keys will always be // strongly reachable while this Class is strongly reachable. Use weak references for both key and value of the mapping instead. cache = new ReferenceMap(AbstractReferenceMap.WEAK, AbstractReferenceMap.WEAK); GENERATED_CLASSES.put(getClass(), cache); }//from w w w . j a va 2s . c om Class<?> generatedClass = cache.get(type); if (generatedClass != null) { return generatedClass.asSubclass(type); } if (Modifier.isPrivate(type.getModifiers())) { throw new GradleException( String.format("Cannot create a proxy class for private class '%s'.", type.getSimpleName())); } if (Modifier.isAbstract(type.getModifiers())) { throw new GradleException( String.format("Cannot create a proxy class for abstract class '%s'.", type.getSimpleName())); } Class<? extends T> subclass; try { ClassMetaData classMetaData = inspectType(type); ClassBuilder<T> builder = start(type, classMetaData); builder.startClass(); if (!DynamicObjectAware.class.isAssignableFrom(type)) { if (ExtensionAware.class.isAssignableFrom(type)) { throw new UnsupportedOperationException( "A type that implements ExtensionAware must currently also implement DynamicObjectAware."); } builder.mixInDynamicAware(); } if (!GroovyObject.class.isAssignableFrom(type)) { builder.mixInGroovyObject(); } builder.addDynamicMethods(); if (classMetaData.conventionAware && !IConventionAware.class.isAssignableFrom(type)) { builder.mixInConventionAware(); } Class noMappingClass = Object.class; for (Class<?> c = type; c != null && noMappingClass == Object.class; c = c.getSuperclass()) { if (c.getAnnotation(NoConventionMapping.class) != null) { noMappingClass = c; } } Set<PropertyMetaData> conventionProperties = new HashSet<PropertyMetaData>(); for (PropertyMetaData property : classMetaData.properties.values()) { if (SKIP_PROPERTIES.contains(property.name)) { continue; } if (property.injector) { builder.addInjectorProperty(property); for (Method getter : property.getters) { builder.applyServiceInjectionToGetter(property, getter); } for (Method setter : property.setters) { builder.applyServiceInjectionToSetter(property, setter); } continue; } boolean needsConventionMapping = false; if (classMetaData.isExtensible()) { for (Method getter : property.getters) { if (!Modifier.isFinal(getter.getModifiers()) && !getter.getDeclaringClass().isAssignableFrom(noMappingClass)) { needsConventionMapping = true; break; } } } if (needsConventionMapping) { conventionProperties.add(property); builder.addConventionProperty(property); for (Method getter : property.getters) { builder.applyConventionMappingToGetter(property, getter); } } if (needsConventionMapping) { for (Method setter : property.setters) { if (!Modifier.isFinal(setter.getModifiers())) { builder.applyConventionMappingToSetter(property, setter); } } } } Set<Method> actionMethods = classMetaData.missingOverloads; for (Method method : actionMethods) { builder.addActionMethod(method); } // Adds a set method for each mutable property for (PropertyMetaData property : classMetaData.properties.values()) { if (property.setters.isEmpty()) { continue; } if (Iterable.class.isAssignableFrom(property.getType())) { // Currently not supported continue; } if (property.setMethods.isEmpty()) { for (Method setter : property.setters) { builder.addSetMethod(property, setter); } } else if (conventionProperties.contains(property)) { for (Method setMethod : property.setMethods) { builder.applyConventionMappingToSetMethod(property, setMethod); } } } for (Constructor<?> constructor : type.getConstructors()) { if (Modifier.isPublic(constructor.getModifiers())) { builder.addConstructor(constructor); } } subclass = builder.generate(); } catch (Throwable e) { throw new GradleException( String.format("Could not generate a proxy class for class %s.", type.getName()), e); } cache.put(type, subclass); cache.put(subclass, subclass); return subclass; }
From source file:com.joliciel.talismane.machineLearning.features.AbstractFeatureParser.java
/** * Get the features corresponding to a particular descriptor by performing * reflection on the corresponding feature class to be instantiated. * @param descriptor// w ww. ja v a 2 s. c om * @param featureClass * @return */ final List<Feature<T, ?>> getFeatures(FunctionDescriptor descriptor, @SuppressWarnings("rawtypes") Class<? extends Feature> featureClass, FunctionDescriptor topLevelDescriptor) { if (featureClass == null) throw new FeatureSyntaxException("No class provided for", descriptor, topLevelDescriptor); List<Feature<T, ?>> features = new ArrayList<Feature<T, ?>>(); int i = 0; List<List<Object>> argumentLists = new ArrayList<List<Object>>(); List<Object> initialArguments = new ArrayList<Object>(); argumentLists.add(initialArguments); for (FunctionDescriptor argumentDescriptor : descriptor.getArguments()) { List<List<Object>> newArgumentLists = new ArrayList<List<Object>>(); for (List<Object> arguments : argumentLists) { if (!argumentDescriptor.isFunction()) { Object literal = argumentDescriptor.getObject(); Object convertedObject = literal; if (literal instanceof String) { StringLiteralFeature<T> stringLiteralFeature = new StringLiteralFeature<T>( (String) literal); convertedObject = stringLiteralFeature; } else if (literal instanceof Boolean) { BooleanLiteralFeature<T> booleanLiteralFeature = new BooleanLiteralFeature<T>( (Boolean) literal); convertedObject = booleanLiteralFeature; } else if (literal instanceof Double) { DoubleLiteralFeature<T> doubleLiteralFeature = new DoubleLiteralFeature<T>( (Double) literal); convertedObject = doubleLiteralFeature; } else if (literal instanceof Integer) { IntegerLiteralFeature<T> integerLiteralFeature = new IntegerLiteralFeature<T>( (Integer) literal); convertedObject = integerLiteralFeature; } else { // do nothing - this was some sort of other object added by getModifiedDescriptors that should // be handled as is. } arguments.add(convertedObject); newArgumentLists.add(arguments); } else { List<Feature<T, ?>> featureArguments = this.parseInternal(argumentDescriptor, topLevelDescriptor); // a single argument descriptor could produce multiple arguments // e.g. when a function with an array argument is mapped onto multiple function calls for (Feature<T, ?> featureArgument : featureArguments) { List<Object> newArguments = new ArrayList<Object>(arguments); newArguments.add(featureArgument); newArgumentLists.add(newArguments); } } // function or object? } // next argument list (under construction from original arguments) argumentLists = newArgumentLists; } // next argument for (List<Object> originalArgumentList : argumentLists) { // add the argument types (i.e. classes) // and convert arrays to multiple constructor calls List<Object[]> argumentsList = new ArrayList<Object[]>(); argumentsList.add(new Object[originalArgumentList.size()]); Class<?>[] argumentTypes = new Class<?>[originalArgumentList.size()]; List<Object[]> newArgumentsList = new ArrayList<Object[]>(); for (i = 0; i < originalArgumentList.size(); i++) { Object arg = originalArgumentList.get(i); if (arg.getClass().isArray()) { // arrays represent multiple constructor calls Object[] argArray = (Object[]) arg; for (Object oneArg : argArray) { for (Object[] arguments : argumentsList) { Object[] newArguments = arguments.clone(); newArguments[i] = oneArg; newArgumentsList.add(newArguments); } } argumentTypes[i] = arg.getClass().getComponentType(); } else { for (Object[] myArguments : argumentsList) { newArgumentsList.add(myArguments); myArguments[i] = arg; } argumentTypes[i] = arg.getClass(); } argumentsList = newArgumentsList; newArgumentsList = new ArrayList<Object[]>(); } // next argument @SuppressWarnings("rawtypes") Constructor<? extends Feature> constructor = null; MONITOR.startTask("findContructor"); try { constructor = ConstructorUtils.getMatchingAccessibleConstructor(featureClass, argumentTypes); if (constructor == null) { Constructor<?>[] constructors = featureClass.getConstructors(); // check if there's a variable argument constructor for (Constructor<?> oneConstructor : constructors) { Class<?>[] parameterTypes = oneConstructor.getParameterTypes(); if (parameterTypes.length >= 1 && argumentsList.size() == 1 && argumentsList.get(0).length >= parameterTypes.length) { Object[] arguments = argumentsList.get(0); Class<?> parameterType = parameterTypes[parameterTypes.length - 1]; if (parameterType.isArray()) { // assume it's a variable-argument constructor // build the argument for this constructor // find a common type for all of the arguments. Object argument = arguments[parameterTypes.length - 1]; Class<?> clazz = null; if (argument instanceof StringFeature) clazz = StringFeature.class; else if (argument instanceof BooleanFeature) clazz = BooleanFeature.class; else if (argument instanceof DoubleFeature) clazz = DoubleFeature.class; else if (argument instanceof IntegerFeature) clazz = IntegerFeature.class; else if (argument instanceof StringCollectionFeature) clazz = StringFeature.class; else { // no good, can't make arrays of this type continue; } Object[] argumentArray = (Object[]) Array.newInstance(clazz, (arguments.length - parameterTypes.length) + 1); int j = 0; for (int k = parameterTypes.length - 1; k < arguments.length; k++) { Object oneArgument = arguments[k]; if (oneArgument instanceof StringCollectionFeature) { @SuppressWarnings("unchecked") StringCollectionFeature<T> stringCollectionFeature = (StringCollectionFeature<T>) oneArgument; StringCollectionFeatureProxy<T> proxy = new StringCollectionFeatureProxy<T>( stringCollectionFeature); oneArgument = proxy; } if (!clazz.isAssignableFrom(oneArgument.getClass())) { throw new FeatureSyntaxException( "Mismatched array types: " + clazz.getSimpleName() + ", " + oneArgument.getClass().getSimpleName(), descriptor, topLevelDescriptor); } argumentArray[j++] = oneArgument; } // next argument Class<?>[] argumentTypesWithArray = new Class<?>[parameterTypes.length]; for (int k = 0; k < parameterTypes.length - 1; k++) { Object oneArgument = arguments[k]; argumentTypesWithArray[k] = oneArgument.getClass(); } argumentTypesWithArray[argumentTypesWithArray.length - 1] = argumentArray .getClass(); constructor = ConstructorUtils.getMatchingAccessibleConstructor(featureClass, argumentTypesWithArray); if (constructor != null) { argumentsList = new ArrayList<Object[]>(); Object[] argumentsWithArray = new Object[parameterTypes.length]; for (int k = 0; k < parameterTypes.length - 1; k++) { Object oneArgument = arguments[k]; argumentsWithArray[k] = oneArgument; } argumentsWithArray[parameterTypes.length - 1] = argumentArray; argumentsList.add(argumentsWithArray); break; } } // constructor takes an array } // exactly one parameter for constructor } // next constructor if (constructor == null) { // See if various conversions allow us to find a constructor // Integer to Double // StringCollectionFeature to StringFeature for (Constructor<?> oneConstructor : constructors) { Class<?>[] parameterTypes = oneConstructor.getParameterTypes(); boolean isMatchingConstructor = false; List<Integer> intParametersToConvert = new ArrayList<Integer>(); List<Integer> stringCollectionParametersToConvert = new ArrayList<Integer>(); List<Integer> customParametersToConvert = new ArrayList<Integer>(); if (parameterTypes.length == argumentTypes.length) { int j = 0; isMatchingConstructor = true; for (Class<?> parameterType : parameterTypes) { if (parameterType.isAssignableFrom(argumentTypes[j]) && !StringCollectionFeature.class.isAssignableFrom(argumentTypes[j])) { // nothing to do here } else if (parameterType.equals(DoubleFeature.class) && IntegerFeature.class.isAssignableFrom(argumentTypes[j])) { intParametersToConvert.add(j); } else if ((parameterType.equals(StringFeature.class) || parameterType.equals(Feature.class)) && StringCollectionFeature.class.isAssignableFrom(argumentTypes[j])) { stringCollectionParametersToConvert.add(j); } else if (this.canConvert(parameterType, argumentTypes[j])) { customParametersToConvert.add(j); } else { isMatchingConstructor = false; break; } j++; } } if (isMatchingConstructor) { @SuppressWarnings({ "rawtypes", "unchecked" }) Constructor<? extends Feature> matchingConstructor = (Constructor<? extends Feature>) oneConstructor; constructor = matchingConstructor; for (Object[] myArguments : argumentsList) { for (int indexToConvert : intParametersToConvert) { @SuppressWarnings("unchecked") IntegerFeature<T> integerFeature = (IntegerFeature<T>) myArguments[indexToConvert]; IntegerToDoubleFeature<T> intToDoubleFeature = new IntegerToDoubleFeature<T>( integerFeature); myArguments[indexToConvert] = intToDoubleFeature; } for (int indexToConvert : stringCollectionParametersToConvert) { @SuppressWarnings("unchecked") StringCollectionFeature<T> stringCollectionFeature = (StringCollectionFeature<T>) myArguments[indexToConvert]; StringCollectionFeatureProxy<T> proxy = new StringCollectionFeatureProxy<T>( stringCollectionFeature); myArguments[indexToConvert] = proxy; } for (int indexToConvert : customParametersToConvert) { @SuppressWarnings("unchecked") Feature<T, ?> argumentToConvert = (Feature<T, ?>) myArguments[indexToConvert]; Feature<T, ?> customArgument = this .convertArgument(parameterTypes[indexToConvert], argumentToConvert); myArguments[indexToConvert] = customArgument; customArgument.addArgument(argumentToConvert); } } break; } // found a matching constructor } // next possible constructor } // still haven't found a constructor, what next? } // didn't find a constructor yet } finally { MONITOR.endTask("findContructor"); } if (constructor == null) throw new NoConstructorFoundException("No constructor found for " + descriptor.getFunctionName() + " (" + featureClass.getName() + ") matching the arguments provided", descriptor, topLevelDescriptor); for (Object[] myArguments : argumentsList) { @SuppressWarnings("rawtypes") Feature feature; try { feature = constructor.newInstance(myArguments); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } @SuppressWarnings("unchecked") Feature<T, ?> genericFeature = (Feature<T, ?>) feature; this.injectDependencies(feature); if (genericFeature instanceof ExternalResourceFeature) { if (this.getExternalResourceFinder() == null) { throw new JolicielException("No external resource finder set."); } @SuppressWarnings("unchecked") ExternalResourceFeature<T> externalResourceFeature = (ExternalResourceFeature<T>) genericFeature; externalResourceFeature.setExternalResourceFinder(this.getExternalResourceFinder()); } else if (genericFeature instanceof ExternalResourceDoubleFeature) { if (this.getExternalResourceFinder() == null) { throw new JolicielException("No external resource finder set."); } @SuppressWarnings("unchecked") ExternalResourceDoubleFeature<T> externalResourceFeature = (ExternalResourceDoubleFeature<T>) genericFeature; externalResourceFeature.setExternalResourceFinder(this.getExternalResourceFinder()); } else if (genericFeature instanceof MultivaluedExternalResourceFeature) { if (this.getExternalResourceFinder() == null) { throw new JolicielException("No external resource finder set."); } @SuppressWarnings("unchecked") MultivaluedExternalResourceFeature<T> externalResourceFeature = (MultivaluedExternalResourceFeature<T>) genericFeature; externalResourceFeature.setExternalResourceFinder(this.getExternalResourceFinder()); } // add this feature's arguments for (Object argument : myArguments) { if (argument instanceof Feature[]) { @SuppressWarnings("unchecked") Feature<T, ?>[] featureArray = (Feature<T, ?>[]) argument; for (Feature<T, ?> oneFeature : featureArray) { genericFeature.addArgument(oneFeature); } } else { @SuppressWarnings("unchecked") Feature<T, ?> featureArgument = (Feature<T, ?>) argument; genericFeature.addArgument(featureArgument); } } Feature<T, ?> convertedFeature = this.convertFeature(genericFeature); features.add(convertedFeature); } // next internal argument list } // next argument list return features; }
From source file:org.kchine.r.server.DirectJNI.java
private RObject getObjectFrom(String expression, String rclass, boolean setAttributes) throws NoMappingAvailable, Exception { log.info(".... quering for =" + expression + " rclass=" + rclass); Rengine e = _rEngine;/* w w w . j a v a 2s . c o m*/ long expressionId = e.rniEval(e.rniParse(expression, 1), 0); RObject result = null; String typeStr = null; int rmode = e.rniExpType(expressionId); boolean isVirtual = e .rniGetBoolArrayI(e.rniEval(e.rniParse("isVirtualClass(\"" + rclass + "\")", 1), 0))[0] == 1; boolean isClass = e.rniGetBoolArrayI(e.rniEval(e.rniParse("isClass(\"" + rclass + "\")", 1), 0))[0] == 1; if (isClass && isVirtual) { String[] unionrclass = e.rniGetStringArray(e.rniEval(e.rniParse("class(" + expression + ")", 1), 0)); System.out.println("Union Class : " + Arrays.toString(unionrclass)); // log.info(">>> union r class=" + unionrclass ); if (rclass.equals("formula")) { result = new RUnknown(e.rniGetIntArray( e.rniEval(e.rniParse("as.integer(serialize(" + expression + ",NULL))", 1), 0))); } else if (unionrclass.length == 1) { RObject o = getObjectFrom(expression, unionrclass[0], true); if (rmode != S4SXP) { if (DirectJNI._s4BeansMapping.get(unionrclass) != null) { o = (RObject) DirectJNI._mappingClassLoader .loadClass(DirectJNI._s4BeansMapping.get(unionrclass)) .getConstructor(new Class[] { o.getClass() }).newInstance(new Object[] { o }); } else { } } String factoryJavaClassName = DirectJNI._factoriesMapping .get(Utils.captalizeFirstChar(rclass) + "FactoryForR" + unionrclass); result = (RObject) DirectJNI._mappingClassLoader.loadClass(factoryJavaClassName).newInstance(); Method setDataM = result.getClass().getMethod("setData", new Class[] { RObject.class }); setDataM.invoke(result, o); } else { if (rmode == VECSXP) { HashSet<String> unionClassSet = new HashSet<String>(); for (int i = 0; i < unionrclass.length; ++i) unionClassSet.add(unionrclass[i]); if (unionClassSet.contains("data.frame")) { result = getObjectFrom(expression, "data.frame", true); } else if (unionClassSet.contains("list")) { result = getObjectFrom(expression, "list", true); } else { RList rlist = (RList) getObjectFrom(expression, "list", true); result = new RS3(rlist.getValue(), rlist.getNames(), unionrclass); } } else { result = new RUnknown(e.rniGetIntArray( e.rniEval(e.rniParse("as.integer(serialize(" + expression + ",NULL))", 1), 0))); } } } else { RVector vector = null; switch (rmode) { case NILSXP: typeStr = "nil = NULL"; result = null; break; case SYMSXP: typeStr = "symbols"; break; case LISTSXP: typeStr = "lists of dotted pairs"; break; case CLOSXP: typeStr = "closures"; result = new RFunction(e.rniGetIntArray( e.rniEval(e.rniParse("as.integer(serialize(" + expression + ",NULL))", 1), 0))); break; case ENVSXP: typeStr = "environments"; String[] vars = e.rniGetStringArray(e.rniEval(e.rniParse("ls(" + expression + ")", 1), 0)); HashMap<String, RObject> data = new HashMap<String, RObject>(); for (int i = 0; i < vars.length; ++i) { String varname = expression + "$" + vars[i]; String varclass = expressionClass(varname); data.put(vars[i], (RObject) getObjectFrom(varname, varclass, true)); } result = new REnvironment(); ((REnvironment) result).setData(data); break; case PROMSXP: typeStr = "promises: [un]evaluated closure"; break; case LANGSXP: typeStr = "language constructs (special lists)"; break; case SPECIALSXP: typeStr = "special forms"; break; case BUILTINSXP: typeStr = "builtin non-special forms"; break; case CHARSXP: typeStr = "'scalar' string type (internal only)"; break; case LGLSXP: { typeStr = "logical vectors"; int[] bAsInt = e.rniGetBoolArrayI(expressionId); boolean[] b = new boolean[bAsInt.length]; for (int i = 0; i < bAsInt.length; ++i) b[i] = bAsInt[i] == 1; String[] names = null; long namesId = e.rniGetAttr(expressionId, "names"); if (namesId != 0 && e.rniExpType(namesId) == STRSXP) { names = e.rniGetStringArray(namesId); } int[] isNaIdx = e.rniGetIntArray(e.rniEval( e.rniParse("(0:(length(" + expression + ")-1))[is.na(" + expression + ")]", 1), 0)); vector = new RLogical(b, isNaIdx.length == 0 ? null : isNaIdx, names); if (rclass.equals("logical") || rclass.equals("vector")) { result = vector; } else if (rclass.equals("matrix") || rclass.equals("array")) { if (rclass.equals("matrix")) { result = new RMatrix(); } else if (rclass.equals("array")) { result = new RArray(); } ((RArray) result).setDim(e.rniGetIntArray(e.rniGetAttr(expressionId, "dim"))); ((RArray) result).setValue(vector); ((RArray) result).setDimnames((RList) getObjectFrom("dimnames(" + expression + ")", true)); } else { result = vector; } if (setAttributes && (e.rniGetBoolArrayI( e.rniEval(e.rniParse("!is.null(attributes(" + expression + "))", 1), 0))[0] == 1)) { result.setAttributes((RList) getObjectFrom("attributes(" + expression + ")", "list", false)); } break; } case INTSXP: { typeStr = "integer vectors"; String[] names = null; long namesId = e.rniGetAttr(expressionId, "names"); if (namesId != 0 && e.rniExpType(namesId) == STRSXP) { names = e.rniGetStringArray(namesId); } int[] isNaIdx = e.rniGetIntArray(e.rniEval( e.rniParse("(0:(length(" + expression + ")-1))[is.na(" + expression + ")]", 1), 0)); vector = new RInteger(e.rniGetIntArray(expressionId), isNaIdx.length == 0 ? null : isNaIdx, names); if (rclass.equals("integer") || rclass.equals("vector")) { result = vector; } else if (rclass.equals("matrix") || rclass.equals("array")) { result = rclass.equals("matrix") ? new RMatrix() : new RArray(); ((RArray) result).setDim(e.rniGetIntArray(e.rniGetAttr(expressionId, "dim"))); ((RArray) result).setValue(vector); ((RArray) result).setDimnames((RList) getObjectFrom("dimnames(" + expression + ")", true)); } else if (rclass.equals("factor")) { String[] levels = e.rniGetStringArray(e.rniGetAttr(expressionId, "levels")); result = new RFactor(levels, e.rniGetIntArray(expressionId)); } else { result = vector; } if (setAttributes && (e.rniGetBoolArrayI( e.rniEval(e.rniParse("!is.null(attributes(" + expression + "))", 1), 0))[0] == 1)) { result.setAttributes((RList) getObjectFrom("attributes(" + expression + ")", "list", false)); } break; } case REALSXP: { typeStr = "real variables"; String[] names = null; long namesId = e.rniGetAttr(expressionId, "names"); if (namesId != 0 && e.rniExpType(namesId) == STRSXP) { names = e.rniGetStringArray(namesId); } int[] isNaIdx = e.rniGetIntArray(e.rniEval( e.rniParse("(0:(length(" + expression + ")-1))[is.na(" + expression + ")]", 1), 0)); vector = new RNumeric(e.rniGetDoubleArray(expressionId), isNaIdx.length == 0 ? null : isNaIdx, names); if (rclass.equals("numeric") || rclass.equals("double") || rclass.equals("vector")) { result = vector; } else if (rclass.equals("matrix") || rclass.equals("array")) { result = rclass.equals("matrix") ? new RMatrix() : new RArray(); ((RArray) result).setDim(e.rniGetIntArray(e.rniGetAttr(expressionId, "dim"))); ((RArray) result).setValue(vector); ((RArray) result).setDimnames((RList) getObjectFrom("dimnames(" + expression + ")", true)); } else { result = vector; } if (setAttributes && (e.rniGetBoolArrayI( e.rniEval(e.rniParse("!is.null(attributes(" + expression + "))", 1), 0))[0] == 1)) { result.setAttributes((RList) getObjectFrom("attributes(" + expression + ")", "list", false)); } break; } case CPLXSXP: { typeStr = "complex variables"; double[] c_real = e.rniGetDoubleArray(e.rniEval(e.rniParse("Re(" + expression + ")", 1), 0)); double[] c_imaginary = e.rniGetDoubleArray(e.rniEval(e.rniParse("Im(" + expression + ")", 1), 0)); String[] names = null; long namesId = e.rniGetAttr(expressionId, "names"); if (namesId != 0 && e.rniExpType(namesId) == STRSXP) { names = e.rniGetStringArray(namesId); } int[] isNaIdx = e.rniGetIntArray(e.rniEval( e.rniParse("(0:(length(" + expression + ")-1))[is.na(" + expression + ")]", 1), 0)); vector = new RComplex(c_real, c_imaginary, isNaIdx.length == 0 ? null : isNaIdx, names); if (rclass.equals("complex") || rclass.equals("vector")) { result = vector; } else if (rclass.equals("matrix") || rclass.equals("array")) { result = rclass.equals("matrix") ? new RMatrix() : new RArray(); ((RArray) result).setDim(e.rniGetIntArray(e.rniGetAttr(expressionId, "dim"))); ((RArray) result).setValue(vector); ((RArray) result).setDimnames((RList) getObjectFrom("dimnames(" + expression + ")", true)); } else { result = vector; } if (setAttributes && (e.rniGetBoolArrayI( e.rniEval(e.rniParse("!is.null(attributes(" + expression + "))", 1), 0))[0] == 1)) { result.setAttributes((RList) getObjectFrom("attributes(" + expression + ")", "list", false)); } break; } case STRSXP: { typeStr = "string vectors"; String[] names = null; long namesId = e.rniGetAttr(expressionId, "names"); if (namesId != 0 && e.rniExpType(namesId) == STRSXP) { names = e.rniGetStringArray(namesId); } int[] isNaIdx = e.rniGetIntArray(e.rniEval( e.rniParse("(0:(length(" + expression + ")-1))[is.na(" + expression + ")]", 1), 0)); vector = new RChar(e.rniGetStringArray(expressionId), isNaIdx.length == 0 ? null : isNaIdx, names); if (rclass.equals("character") || rclass.equals("vector")) { result = vector; } else if (rclass.equals("matrix") || rclass.equals("array")) { result = rclass.equals("matrix") ? new RMatrix() : new RArray(); ((RArray) result).setDim(e.rniGetIntArray(e.rniGetAttr(expressionId, "dim"))); ((RArray) result).setValue(vector); ((RArray) result).setDimnames((RList) getObjectFrom("dimnames(" + expression + ")", true)); } else { result = vector; } if (setAttributes && (e.rniGetBoolArrayI( e.rniEval(e.rniParse("!is.null(attributes(" + expression + "))", 1), 0))[0] == 1)) { result.setAttributes((RList) getObjectFrom("attributes(" + expression + ")", "list", false)); } break; } case DOTSXP: typeStr = "dot-dot-dot object"; break; case ANYSXP: typeStr = "make 'any' args work"; break; case VECSXP: { typeStr = "generic vectors"; String[] names = null; RObject[] objects = null; long namesId = e.rniGetAttr(expressionId, "names"); if (namesId != 0 && e.rniExpType(namesId) == STRSXP) { names = e.rniGetStringArray(namesId); } long[] objectIds = e.rniGetVector(expressionId); int[] types = new int[objectIds.length]; for (int i = 0; i < objectIds.length; ++i) { types[i] = e.rniExpType(objectIds[i]); } if (objectIds.length > 0) { objects = new RObject[objectIds.length]; for (int i = 0; i < objects.length; ++i) { String varname = expression + "[[" + (i + 1) + "]]"; if (!isNull(varname)) { objects[i] = getObjectFrom(varname, expressionClass(varname), true); } } } RList rlist = new RList(objects, names); if (rclass.equals("list")) { result = rlist; } else if (rclass.equals("data.frame")) { // String[] rowNames = // e.rniGetStringArray(e.rniGetAttr(expressionId, // "row.names")); String[] rowNames = e .rniGetStringArray(e.rniEval(e.rniParse("row.names(" + expression + ")", 1), 0)); result = new RDataFrame(rlist, rowNames); } else { boolean isObject = e .rniGetBoolArrayI(e.rniEval(e.rniParse("is.object(" + expression + ")", 1), 0))[0] == 1; if (isObject && !isClass) result = new RS3(rlist.getValue(), rlist.getNames(), e.rniGetStringArray(e.rniEval(e.rniParse("class(" + expression + ")", 1), 0))); } if (setAttributes && (e.rniGetBoolArrayI( e.rniEval(e.rniParse("!is.null(attributes(" + expression + "))", 1), 0))[0] == 1)) { result.setAttributes((RList) getObjectFrom("attributes(" + expression + ")", "list", false)); } break; } case EXPRSXP: typeStr = "expressions vectors"; break; case BCODESXP: typeStr = "byte code"; break; case EXTPTRSXP: typeStr = "external pointer"; break; case WEAKREFSXP: typeStr = "weak reference"; break; case RAWSXP: typeStr = "raw bytes"; result = new RRaw(e.rniGetIntArray(e.rniEval(e.rniParse("as.integer(" + expression + ")", 1), 0))); break; case S4SXP: Class<?> s4Java_class = null; try { s4Java_class = DirectJNI._mappingClassLoader.loadClass(DirectJNI._s4BeansMapping.get(rclass)); } catch (Exception ex) { result = new RUnknown(e.rniGetIntArray( e.rniEval(e.rniParse("as.integer(serialize(" + expression + ",NULL))", 1), 0))); break; } long slotsId = e.rniEval(e.rniParse("getSlots(\"" + rclass + "\")", 1), 0); String[] slots = e.rniGetStringArray(e.rniGetAttr(slotsId, "names")); String[] slotsRClasses = e.rniGetStringArray(slotsId); Object[] params = new Object[slots.length]; for (int i = 0; i < slots.length; ++i) { params[i] = getObjectFrom(expression + "@" + slots[i], slotsRClasses[i], true); } Constructor<?> constr = null; for (int i = 0; i < s4Java_class.getConstructors().length; ++i) { if (s4Java_class.getConstructors()[i].getParameterTypes().length > 0) { constr = s4Java_class.getConstructors()[i]; break; } } result = (RObject) constr.newInstance(params); typeStr = "S4 object"; break; case FUNSXP: typeStr = "Closure or Builtin"; break; default: throw new Exception("type of <" + expression + "> not recognized"); } } if (false) log.info("TYPE STR FOR<" + expression + ">:" + typeStr + " result:" + result + " type hint was : " + rclass); return result; }
From source file:lu.fisch.unimozer.Diagram.java
@Override public void actionPerformed(ActionEvent e) { if (isEnabled()) { if (e.getSource() instanceof JMenuItem) { JMenuItem item = (JMenuItem) e.getSource(); if (item.getText().equals("Compile")) { compile();/* w w w . ja v a2s. c o m*/ } else if (item.getText().equals("Remove class") && mouseClass != null) { int answ = JOptionPane.showConfirmDialog(frame, "Are you sure to remove the class " + mouseClass.getFullName() + "", "Remove a class", JOptionPane.YES_NO_OPTION); if (answ == JOptionPane.YES_OPTION) { cleanAll();// clean(mouseClass); removedClasses.add(mouseClass.getFullName()); classes.remove(mouseClass.getFullName()); mouseClass = null; updateEditor(); repaint(); objectizer.repaint(); } } else if (mouseClass.getName().contains("abstract")) { JOptionPane.showMessageDialog(frame, "Can't create an object of an abstract class ...", "Instatiation error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } else if (item.getText().startsWith("new")) // we have constructor { Logger.getInstance().log("Click on <new> registered"); // get full signature String fSign = item.getText(); if (fSign.startsWith("new")) fSign = fSign.substring(3).trim(); // get signature final String fullSign = fSign; Logger.getInstance().log("fullSign = " + fSign); final String sign = mouseClass.getSignatureByFullSignature(fullSign); Logger.getInstance().log("sign = " + sign); Logger.getInstance().log("Creating runnable ..."); Runnable r = new Runnable() { @Override public void run() { //System.out.println("Calling method (full): "+fullSign); //System.out.println("Calling method : "+sign); try { Logger.getInstance().log("Loading the class <" + mouseClass.getName() + ">"); Class<?> cla = Runtime5.getInstance().load(mouseClass.getFullName()); //mouseClass.load(); Logger.getInstance().log("Loaded!"); // check if we need to specify a generic class boolean cont = true; String generics = ""; TypeVariable[] tv = cla.getTypeParameters(); Logger.getInstance().log("Got TypeVariables with length = " + tv.length); if (tv.length > 0) { LinkedHashMap<String, String> gms = new LinkedHashMap<String, String>(); for (int i = 0; i < tv.length; i++) { gms.put(tv[i].getName(), ""); } MethodInputs gi = new MethodInputs(frame, gms, "Generic type declaration", "Please specify the generic types"); cont = gi.OK; // build the string generics = "<"; Object[] keys = gms.keySet().toArray(); mouseClass.generics.clear(); for (int in = 0; in < keys.length; in++) { String kname = (String) keys[in]; // save generic type to myClass mouseClass.generics.put(kname, gi.getValueFor(kname)); generics += gi.getValueFor(kname) + ","; } generics = generics.substring(0, generics.length() - 1); generics += ">"; } if (cont == true) { Logger.getInstance().log("Getting the constructors."); Constructor[] constr = cla.getConstructors(); for (int c = 0; c < constr.length; c++) { // get signature String full = objectizer.constToFullString(constr[c]); Logger.getInstance().log("full = " + full); /* String full = constr[c].getName(); full+="("; Class<?>[] tvm = constr[c].getParameterTypes(); for(int t=0;t<tvm.length;t++) { String sn = tvm[t].toString(); sn=sn.substring(sn.lastIndexOf('.')+1,sn.length()); if(sn.startsWith("class")) sn=sn.substring(5).trim(); // array is shown as ";" ??? if(sn.endsWith(";")) { sn=sn.substring(0,sn.length()-1)+"[]"; } full+= sn+", "; } if(tvm.length>0) full=full.substring(0,full.length()-2); full+= ")"; */ /*System.out.println("Loking for S : "+sign); System.out.println("Loking for FS: "+fullSign); System.out.println("Found: "+full);*/ if (full.equals(sign) || full.equals(fullSign)) { Logger.getInstance().log("We are in!"); //editor.setEnabled(false); //Logger.getInstance().log("Editor disabled"); String name; Logger.getInstance().log("Ask user for a name."); do { String propose = mouseClass.getShortName().substring(0, 1) .toLowerCase() + mouseClass.getShortName().substring(1); int count = 0; String prop = propose + count; while (objectizer.hasObject(prop) == true) { count++; prop = propose + count; } name = (String) JOptionPane.showInputDialog(frame, "Please enter the name for you new instance of " + mouseClass.getShortName() + "", "Create object", JOptionPane.QUESTION_MESSAGE, null, null, prop); if (Java.isIdentifierOrNull(name) == false) { JOptionPane.showMessageDialog(frame, "" + name + " is not a correct identifier.", "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } else if (objectizer.hasObject(name) == true) { JOptionPane.showMessageDialog(frame, "An object with the name " + name + " already exists.\nPlease choose another name ...", "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } } while (Java.isIdentifierOrNull(name) == false || objectizer.hasObject(name) == true); Logger.getInstance().log("name = " + name); if (name != null) { Logger.getInstance().log("Need to get inputs ..."); LinkedHashMap<String, String> inputs = mouseClass .getInputsBySignature(sign); if (inputs.size() == 0) inputs = mouseClass.getInputsBySignature(fullSign); //System.out.println("1) "+sign); //System.out.println("2) "+fullSign); MethodInputs mi = null; boolean go = true; if (inputs.size() > 0) { mi = new MethodInputs(frame, inputs, full, mouseClass.getJavaDocBySignature(sign)); go = mi.OK; } Logger.getInstance().log("go = " + go); if (go == true) { Logger.getInstance().log("Building string ..."); //Object arglist[] = new Object[inputs.size()]; String constructor = "new " + mouseClass.getFullName() + generics + "("; if (inputs.size() > 0) { Object[] keys = inputs.keySet().toArray(); for (int in = 0; in < keys.length; in++) { String kname = (String) keys[in]; //String type = inputs.get(kname); //if(type.equals("int")) { arglist[in] = Integer.valueOf(mi.getValueFor(kname)); } //else if(type.equals("short")) { arglist[in] = Short.valueOf(mi.getValueFor(kname)); } //else if(type.equals("byte")) { arglist[in] = Byte.valueOf(mi.getValueFor(kname)); } //else if(type.equals("long")) { arglist[in] = Long.valueOf(mi.getValueFor(kname)); } //else if(type.equals("float")) { arglist[in] = Float.valueOf(mi.getValueFor(kname)); } //else if(type.equals("double")) { arglist[in] = Double.valueOf(mi.getValueFor(kname)); } //else if(type.equals("boolean")) { arglist[in] = Boolean.valueOf(mi.getValueFor(kname)); } //else arglist[in] = mi.getValueFor(kname); String val = mi.getValueFor(kname); if (val.equals("")) val = "null"; else { String type = mi.getTypeFor(kname); if (type.toLowerCase().equals("byte")) constructor += "Byte.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("short")) constructor += "Short.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("float")) constructor += "Float.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("long")) constructor += "Long.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("double")) constructor += "Double.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("char")) constructor += "'" + val + "',"; else constructor += val + ","; } //constructor+=mi.getValueFor(kname)+","; } constructor = constructor.substring(0, constructor.length() - 1); } //System.out.println(arglist); constructor += ")"; //System.out.println(constructor); Logger.getInstance().log("constructor = " + constructor); //LOAD: //addLibs(); Object obj = Runtime5.getInstance().getInstance(name, constructor); //mouseClass.getInstance(name, constructor); Logger.getInstance().log("Objet is now instantiated!"); //Runtime.getInstance().interpreter.getNameSpace().i //System.out.println(obj.getClass().getSimpleName()); //Object obj = constr[c].newInstance(arglist); MyObject myo = objectizer.addObject(name, obj); myo.setMyClass(mouseClass); obj = null; cla = null; } objectizer.repaint(); Logger.getInstance().log("Objectizer repainted ..."); repaint(); Logger.getInstance().log("Diagram repainted ..."); } //editor.setEnabled(true); //Logger.getInstance().log("Editor enabled again ..."); } } } } catch (Exception ex) { //ex.printStackTrace(); MyError.display(ex); JOptionPane.showMessageDialog(frame, ex.toString(), "Instantiation error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } } }; Thread t = new Thread(r); t.start(); } else // we have a static method { try { // get full signature String fullSign = ((JMenuItem) e.getSource()).getText(); // get signature String sign = mouseClass.getSignatureByFullSignature(fullSign).replace(", ", ","); String complete = mouseClass.getCompleteSignatureBySignature(sign).replace(", ", ","); /*System.out.println("Calling method (full): "+fullSign); System.out.println("Calling method : "+sign); System.out.println("Calling method (comp): "+complete);/**/ // find method Class c = Runtime5.getInstance().load(mouseClass.getFullName()); Method m[] = c.getMethods(); for (int i = 0; i < m.length; i++) { /*String full = ""; full+= m[i].getReturnType().getSimpleName(); full+=" "; full+= m[i].getName(); full+= "("; Class<?>[] tvm = m[i].getParameterTypes(); LinkedHashMap<String,String> genericInputs = new LinkedHashMap<String,String>(); for(int t=0;t<tvm.length;t++) { String sn = tvm[t].toString(); //System.out.println(sn); if(sn.startsWith("class")) sn=sn.substring(5).trim(); sn=sn.substring(sn.lastIndexOf('.')+1,sn.length()); // array is shown as ";" ??? if(sn.endsWith(";")) { sn=sn.substring(0,sn.length()-1)+"[]"; } full+= sn+", "; genericInputs.put("param"+t,sn); } if(tvm.length>0) full=full.substring(0,full.length()-2); full+= ")";*/ String full = objectizer.toFullString(m[i]); LinkedHashMap<String, String> genericInputs = objectizer.getInputsReplaced(m[i], null); /*System.out.println("Looking for S : "+sign); System.out.println("Looking for FS: "+fullSign); System.out.println("Found : "+full);*/ if (full.equals(sign) || full.equals(fullSign)) { LinkedHashMap<String, String> inputs = mouseClass.getInputsBySignature(sign); //Objectizer.printLinkedHashMap("inputs", inputs); if (inputs.size() != genericInputs.size()) { inputs = genericInputs; } //Objectizer.printLinkedHashMap("inputs", inputs); MethodInputs mi = null; boolean go = true; if (inputs.size() > 0) { mi = new MethodInputs(frame, inputs, full, mouseClass.getJavaDocBySignature(sign)); go = mi.OK; } if (go == true) { try { String method = mouseClass.getFullName() + "." + m[i].getName() + "("; if (inputs.size() > 0) { Object[] keys = inputs.keySet().toArray(); //int cc = 0; for (int in = 0; in < keys.length; in++) { String name = (String) keys[in]; String val = mi.getValueFor(name); if (val.equals("")) method += val + "null,"; else { String type = mi.getTypeFor(name); if (type.toLowerCase().equals("byte")) method += "Byte.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("short")) method += "Short.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("float")) method += "Float.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("long")) method += "Long.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("double")) method += "Double.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("char")) method += "'" + val + "',"; else method += val + ","; } //if (val.equals("")) val="null"; //method+=val+","; } if (!method.endsWith("(")) method = method.substring(0, method.length() - 1); } method += ")"; //System.out.println(method); // Invoke method in a new thread final String myMeth = method; Runnable r = new Runnable() { public void run() { try { Object retobj = Runtime5.getInstance().executeMethod(myMeth); if (retobj != null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE, Unimozer.IMG_INFO); } catch (EvalError ex) { JOptionPane.showMessageDialog(frame, ex.toString(), "Invokation error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); MyError.display(ex); } } }; Thread t = new Thread(r); t.start(); //System.out.println(method); //Object retobj = Runtime5.getInstance().executeMethod(method); //if(retobj!=null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE,Unimozer.IMG_INFO); } catch (Throwable ex) { JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); MyError.display(ex); } } } } } catch (Exception ex) { JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); MyError.display(ex); } } } } }
From source file:com.clark.func.Functions.java
/** * <p>/*from w w w. java 2s .c o m*/ * Find an accessible constructor with compatible parameters. Compatible * parameters mean that every method parameter is assignable from the given * parameters. In other words, it finds constructor that will take the * parameters given. * </p> * * <p> * First it checks if there is constructor matching the exact signature. If * no such, all the constructors of the class are tested if their signatures * are assignment compatible with the parameter types. The first matching * constructor is returned. * </p> * * @param cls * find constructor for this class * @param parameterTypes * find method with compatible parameters * @return a valid Constructor object. If there's no matching constructor, * returns <code>null</code>. */ @SuppressWarnings("unchecked") public static <T> Constructor<T> getMatchingAccessibleConstructor(Class<T> cls, Class<?>... parameterTypes) { // see if we can find the constructor directly // most of the time this works and it's much faster try { Constructor<T> ctor = cls.getConstructor(parameterTypes); setAccessibleWorkaround(ctor); return ctor; } catch (NoSuchMethodException e) { /* SWALLOW */ } Constructor<T> result = null; // search through all constructors Constructor<?>[] ctors = cls.getConstructors(); for (int i = 0; i < ctors.length; i++) { // compare parameters if (isAssignable(parameterTypes, ctors[i].getParameterTypes(), true)) { // get accessible version of method Constructor<T> ctor = getAccessibleConstructor((Constructor<T>) ctors[i]); if (ctor != null) { setAccessibleWorkaround(ctor); if (result == null || compareParameterTypes(ctor.getParameterTypes(), result.getParameterTypes(), parameterTypes) < 0) { result = ctor; } } } } return result; }