List of usage examples for java.lang Class getTypeParameters
@SuppressWarnings("unchecked") public TypeVariable<Class<T>>[] getTypeParameters()
From source file:se.vgregion.dao.domain.patterns.repository.db.jpa.AbstractJpaRepository.java
/** * Get the actual type arguments a child class has used to extend a generic base class. * /* w ww . ja va 2 s .co m*/ * @param childClass * the child class * @return a list of the raw classes for the actual type arguments. * * @see http://www.artima.com/weblogs/viewpost.jsp?thread=208860 */ private List<Class<? extends T>> getTypeArguments( @SuppressWarnings("rawtypes") Class<? extends AbstractJpaRepository> childClass) { Map<Type, Type> resolvedTypes = new HashMap<Type, Type>(); Type type = childClass; // start walking up the inheritance hierarchy until we hit this class while (!getClass(type).equals(AbstractJpaRepository.class)) { if (type instanceof Class) { // there is no useful information for us in raw types, so just keep going. type = ((Class<?>) type).getGenericSuperclass(); } else { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> rawType = (Class<?>) parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); TypeVariable<?>[] typeParameters = rawType.getTypeParameters(); for (int i = 0; i < actualTypeArguments.length; i++) { resolvedTypes.put(typeParameters[i], actualTypeArguments[i]); } if (!rawType.equals(AbstractJpaRepository.class)) { type = rawType.getGenericSuperclass(); } } } // finally, for each actual type argument provided to baseClass, determine (if possible) // the raw class for that type argument. Type[] actualTypeArguments; if (type instanceof Class) { actualTypeArguments = ((Class<?>) type).getTypeParameters(); } else { actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments(); } List<Class<? extends T>> typeArgumentsAsClasses = new ArrayList<Class<? extends T>>(); // resolve types by chasing down type variables. for (Type baseType : actualTypeArguments) { while (resolvedTypes.containsKey(baseType)) { baseType = resolvedTypes.get(baseType); } typeArgumentsAsClasses.add(getClass(baseType)); } return typeArgumentsAsClasses; }
From source file:springfox.documentation.schema.TypeNameExtractor.java
private String genericTypeName(ResolvedType resolvedType, ModelContext context) { Class<?> erasedType = resolvedType.getErasedType(); GenericTypeNamingStrategy namingStrategy = context.getGenericNamingStrategy(); ModelNameContext nameContext = new ModelNameContext(resolvedType.getErasedType(), context.getDocumentationType()); String simpleName = fromNullable(typeNameFor(erasedType)).or(typeName(nameContext)); StringBuilder sb = new StringBuilder(String.format("%s%s", simpleName, namingStrategy.getOpenGeneric())); boolean first = true; for (int index = 0; index < erasedType.getTypeParameters().length; index++) { ResolvedType typeParam = resolvedType.getTypeParameters().get(index); if (first) { sb.append(innerTypeName(typeParam, context)); first = false;// ww w.ja v a2 s. co m } else { sb.append(String.format("%s%s", namingStrategy.getTypeListDelimiter(), innerTypeName(typeParam, context))); } } sb.append(namingStrategy.getCloseGeneric()); return sb.toString(); }
From source file:com.link_intersystems.lang.reflect.Class2.java
private Type doGetBoundType(ParameterizedType parameterizedType, TypeVariable<?> typeVariable) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); Type rawType = parameterizedType.getRawType(); if (rawType instanceof Class<?>) { Class<?> rawTypeClass = (Class<?>) rawType; TypeVariable<?>[] typeParameters = rawTypeClass.getTypeParameters(); for (int i = 0; i < typeParameters.length; i++) { TypeVariable<?> typeParameter = typeParameters[i]; if (typeParameter.equals(typeVariable)) { return actualTypeArguments[i]; }/*from w w w .j a v a 2 s .c o m*/ } } return null; }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private Object getObject(Class claz, List<Type> heirarchies) throws Exception { if (claz.isEnum()) return claz.getEnumConstants()[0]; if (isMap(claz)) { return getMapValue(claz, claz.getTypeParameters(), heirarchies); } else if (isCollection(claz)) { return getListSetValue(claz, claz.getTypeParameters(), heirarchies); } else if (claz.isInterface() || Modifier.isAbstract(claz.getModifiers())) { return null; }//from w w w . j a v a2 s .co m if (heirarchies.contains(claz) || heirarchies.size() >= 2) return null; heirarchies.add(claz); Constructor cons = null; try { cons = claz.getConstructor(new Class[] {}); } catch (Exception e) { getLog().error("No public no-args constructor found for class " + claz.getName()); return null; } Object object = cons.newInstance(new Object[] {}); List<Field> allFields = getAllFields(claz); for (Field field : allFields) { if (Modifier.isStatic(field.getModifiers())) continue; if (!field.isAccessible()) { field.setAccessible(true); } List<Type> fheirlst = new ArrayList<Type>(heirarchies); if (isDebugEnabled()) getLog().info("Parsing Class " + getHeirarchyStr(fheirlst) + " field " + field.getName() + " type " + field.getType().equals(boolean.class)); if (isPrimitive(field.getType())) { field.set(object, getPrimitiveValue(field.getType())); } else if (isMap(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); field.set(object, getMapValue(field.getType(), type.getActualTypeArguments(), fheirlst)); } else if (isCollection(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); field.set(object, getListSetValue(field.getType(), type.getActualTypeArguments(), fheirlst)); } else if (!claz.equals(field.getType())) { Object fieldval = getObject(field.getType(), fheirlst); field.set(object, fieldval); } else if (claz.equals(field.getType())) { if (isDebugEnabled()) getLog().info("Ignoring recursive fields..."); } } return object; }
From source file:ch.ralscha.extdirectspring.util.ParametersResolver.java
private Object convertValue(Object value, ParameterInfo methodParameter) { if (value != null) { Class<?> rawType = methodParameter.getType(); if (rawType.equals(value.getClass())) { return value; } else if (this.conversionService.canConvert(TypeDescriptor.forObject(value), methodParameter.getTypeDescriptor())) { try { return this.conversionService.convert(value, TypeDescriptor.forObject(value), methodParameter.getTypeDescriptor()); } catch (ConversionFailedException e) { // ignore this exception for collections and arrays. // try to convert the value with jackson TypeFactory typeFactory = this.jsonHandler.getMapper().getTypeFactory(); if (methodParameter.getTypeDescriptor().isCollection()) { JavaType elemType = typeFactory.constructType( methodParameter.getTypeDescriptor().getElementTypeDescriptor().getType()); TypeVariable<?>[] vars = rawType.getTypeParameters(); TypeBindings bindings; if ((vars == null) || (vars.length != 1)) { bindings = TypeBindings.emptyBindings(); } else { bindings = TypeBindings.create(rawType, elemType); }//from ww w . j a va 2 s .c o m JavaType superClass = null; Class<?> parent = rawType.getSuperclass(); if (parent != null) { superClass = TypeFactory.unknownType(); } JavaType type = CollectionType.construct(rawType, bindings, superClass, null, elemType); return this.jsonHandler.convertValue(value, type); } else if (methodParameter.getTypeDescriptor().isArray()) { JavaType type = typeFactory.constructArrayType( methodParameter.getTypeDescriptor().getElementTypeDescriptor().getType()); return this.jsonHandler.convertValue(value, type); } throw e; } } else { return this.jsonHandler.convertValue(value, rawType); } } else if (methodParameter.isJavaUtilOptional()) { return javaUtilOptionalEmpty; } return null; }
From source file:net.firejack.platform.core.utils.Factory.java
public Class getGenericParameterClass(Class actualClass, Class genericClass, int parameterIndex) { if (!genericClass.isAssignableFrom(actualClass) || genericClass.equals(actualClass)) { throw new IllegalArgumentException( "Class " + genericClass.getName() + " is not a superclass of " + actualClass.getName() + "."); }/* w w w. j a va2 s .c o m*/ Stack<ParameterizedType> types = new Stack<ParameterizedType>(); Class clazz = actualClass; while (true) { Type currentType = genericClass.isInterface() ? getGenericInterface(clazz, genericClass) : clazz.getGenericSuperclass(); Type rawType; if (currentType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) currentType; types.push(type); rawType = type.getRawType(); } else { types.clear(); rawType = currentType; } if (!rawType.equals(genericClass)) { clazz = (Class) rawType; } else { break; } } if (types.isEmpty()) { return (Class) genericClass.getTypeParameters()[parameterIndex].getGenericDeclaration(); } Type result = types.pop().getActualTypeArguments()[parameterIndex]; while (result instanceof TypeVariable && !types.empty()) { int actualArgumentIndex = getParameterTypeDeclarationIndex((TypeVariable) result); ParameterizedType type = types.pop(); result = type.getActualTypeArguments()[actualArgumentIndex]; } if (result instanceof TypeVariable) { throw new IllegalStateException("Unable to resolve type variable " + result + "." + " Try to replace instances of parametrized class with its non-parameterized subtype."); } if (result instanceof ParameterizedType) { result = ((ParameterizedType) result).getRawType(); } if (result == null) { throw new IllegalStateException( "Unable to determine actual parameter type for " + actualClass.getName() + "."); } if (!(result instanceof Class)) { throw new IllegalStateException( "Actual parameter type for " + actualClass.getName() + " is not a Class."); } return (Class) result; }
From source file:com.link_intersystems.lang.reflect.Class2.java
/** * The string representation of a {@link Class2}. * * <ul>/*from w ww. j a v a 2 s . c o m*/ * <li> * Types are represented by their canonical name. If a type is a * "well-known" type (all types in java.lang) the type's simple * name is used. E.g. String - java.util.List.</li> * <ul> * <li> * Arrays are represented by their type and appended by []. E.g. int[] * String[] java.beans.PropertyDescriptor[].</li> * * @param wellKnownPackages * packages that are "well known" will not be printed * in the string representation. E.g. if java.lang is defined as * well known the Class2 that represents a String class will be * printed just as "String" and not java.lang.String. * * @return a string representation of this {@link Class2}; * @since 1.0.0.0 */ public String toString(String... wellKnownPackages) { Assert.notNull("wellKnownPackages", wellKnownPackages); StringBuilder toStringBuilder = new StringBuilder(); Class<?> clazz = getType(); boolean isArray = clazz.isArray(); if (isArray) { clazz = clazz.getComponentType(); } Package clazzPackage = clazz.getPackage(); String packageName = StringUtils.EMPTY; if (clazzPackage != null) { packageName = clazzPackage.getName(); } boolean isWellKnownPackage = Arrays.binarySearch(wellKnownPackages, packageName) > -1; if (isWellKnownPackage) { toStringBuilder.append(clazz.getSimpleName()); } else { toStringBuilder.append(clazz.getCanonicalName()); } TypeVariable<?>[] typeParameters = clazz.getTypeParameters(); String typeParametersToString = typeParametersToString(typeParameters); toStringBuilder.append(typeParametersToString); if (isArray) { toStringBuilder.append("[]"); } return toStringBuilder.toString(); }
From source file:com.alibaba.fastjson.parser.ParserConfig.java
public ObjectDeserializer createJavaBeanDeserializer(Class<?> clazz, Type type) { boolean asmEnable = this.asmEnable & !this.fieldBased; if (asmEnable) { JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); if (jsonType != null) { Class<?> deserializerClass = jsonType.deserializer(); if (deserializerClass != Void.class) { try { Object deseralizer = deserializerClass.newInstance(); if (deseralizer instanceof ObjectDeserializer) { return (ObjectDeserializer) deseralizer; }/* ww w.ja v a 2s.c om*/ } catch (Throwable e) { // skip } } asmEnable = jsonType.asm(); } if (asmEnable) { Class<?> superClass = JavaBeanInfo.getBuilderClass(clazz, jsonType); if (superClass == null) { superClass = clazz; } for (;;) { if (!Modifier.isPublic(superClass.getModifiers())) { asmEnable = false; break; } superClass = superClass.getSuperclass(); if (superClass == Object.class || superClass == null) { break; } } } } if (clazz.getTypeParameters().length != 0) { asmEnable = false; } if (asmEnable && asmFactory != null && asmFactory.classLoader.isExternalClass(clazz)) { asmEnable = false; } if (asmEnable) { asmEnable = ASMUtils.checkName(clazz.getSimpleName()); } if (asmEnable) { if (clazz.isInterface()) { asmEnable = false; } JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy); if (asmEnable && beanInfo.fields.length > 200) { asmEnable = false; } Constructor<?> defaultConstructor = beanInfo.defaultConstructor; if (asmEnable && defaultConstructor == null && !clazz.isInterface()) { asmEnable = false; } for (FieldInfo fieldInfo : beanInfo.fields) { if (fieldInfo.getOnly) { asmEnable = false; break; } Class<?> fieldClass = fieldInfo.fieldClass; if (!Modifier.isPublic(fieldClass.getModifiers())) { asmEnable = false; break; } if (fieldClass.isMemberClass() && !Modifier.isStatic(fieldClass.getModifiers())) { asmEnable = false; break; } if (fieldInfo.getMember() != null // && !ASMUtils.checkName(fieldInfo.getMember().getName())) { asmEnable = false; break; } JSONField annotation = fieldInfo.getAnnotation(); if (annotation != null // && ((!ASMUtils.checkName(annotation.name())) // || annotation.format().length() != 0 // || annotation.deserializeUsing() != Void.class // || annotation.unwrapped()) || (fieldInfo.method != null && fieldInfo.method.getParameterTypes().length > 1)) { asmEnable = false; break; } if (fieldClass.isEnum()) { // EnumDeserializer ObjectDeserializer fieldDeser = this.getDeserializer(fieldClass); if (!(fieldDeser instanceof EnumDeserializer)) { asmEnable = false; break; } } } } if (asmEnable) { if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) { asmEnable = false; } } if (!asmEnable) { return new JavaBeanDeserializer(this, clazz, type); } JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy); try { return asmFactory.createJavaBeanDeserializer(this, beanInfo); // } catch (VerifyError e) { // e.printStackTrace(); // return new JavaBeanDeserializer(this, clazz, type); } catch (NoSuchMethodException ex) { return new JavaBeanDeserializer(this, clazz, type); } catch (JSONException asmError) { return new JavaBeanDeserializer(this, beanInfo); } catch (Exception e) { throw new JSONException("create asm deserializer error, " + clazz.getName(), e); } }
From source file:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java
@SuppressWarnings("unchecked") public static <T> Optional<T> tryCast(Object val, final Class<T> expected) { if (val == null) { return Optional.empty(); }//from w w w .j ava 2 s. c om if (expected == null) { throw new IllegalArgumentException("Must provide an expected class!"); } if (val instanceof BaseValue<?> && !BaseValue.class.isAssignableFrom(expected)) { return tryCast(((BaseValue<?>) val).get(), expected); } if (val instanceof Supplier) { Supplier<?> fun = (Supplier<?>) val; return tryCast(fun.get(), expected); } if (Text.class.isAssignableFrom(expected)) { if (val instanceof Text) { return TypeUtils.tryOptional(() -> expected.cast(val)); } else { if (val instanceof ItemStack) { return TypeUtils.tryOptional(() -> expected.cast(TextUtils.ofItem((ItemStack) val))); } if (val instanceof Instant) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE .deserialize(PlaceholderAPIPlugin.getInstance().formatter() .format(LocalDateTime.ofInstant((Instant) val, ZoneId.systemDefault()))))); } if (val instanceof Duration) { String dur = formatDuration((Duration) val); return TypeUtils .tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(dur))); } if (val instanceof LocalDateTime) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize( PlaceholderAPIPlugin.getInstance().formatter().format((LocalDateTime) val)))); } if (val instanceof CommandSource) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE .deserialize(String.valueOf(((CommandSource) val).getName())))); } if (val.getClass().isArray()) { List<Text> l2 = unboxPrimitiveArray(val).stream() .map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional()) .collect(Collectors.toList()); return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2))); } if (val instanceof Iterable) { Iterable<?> l = (Iterable<?>) val; // should be safe cause we already checked assignability @SuppressWarnings("serial") final List<Text> l2 = new ArrayList<Object>() { { for (Object o : l) { add(o); } } }.stream().map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional()) .collect(Collectors.toList()); return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2))); } return TypeUtils.tryOptional( () -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(String.valueOf(val)))); } } if (val instanceof String) { if (String.class.isAssignableFrom(expected)) { return tryOptional(() -> expected.cast(val)); } if (expected.isArray() && String.class.isAssignableFrom(expected.getComponentType())) { String v = (String) val; if (v.isEmpty()) { return Optional.empty(); } if (!v.contains("_")) { return tryOptional(() -> expected.cast(new String[] { v })); } String[] x = v.split("_"); if (x.length == 0) { return Optional.empty(); } boolean ne = false; for (String s : x) { ne = ne || !s.isEmpty(); } if (!ne) { return Optional.empty(); } return tryOptional(() -> expected.cast(x)); } if (List.class.isAssignableFrom(expected) && String.class.isAssignableFrom(expected.getTypeParameters()[0].getGenericDeclaration())) { String v = (String) val; if (v.isEmpty()) { return Optional.empty(); } if (!v.contains("_")) { return tryOptional(() -> expected.cast(Collections.singletonList(v))); } String[] x = v.split("_"); if (x.length == 0) { return Optional.empty(); } boolean ne = false; for (String s : x) { ne = ne || !s.isEmpty(); } if (!ne) { return Optional.empty(); } return tryOptional(() -> expected.cast(Arrays.asList(x))); } Optional<T> opt = tryOptional(() -> convertPrimitive((String) val, expected)); if (opt.isPresent()) { return opt; } opt = deserializers.entrySet().stream() .filter(e -> e.getKey().isSubtypeOf(expected) || e.getKey().getRawType().equals(expected)) .map(Map.Entry::getValue).map(f -> tryOptional(() -> f.apply((String) val))) .flatMap(unmapOptional()).findAny().flatMap(o -> tryOptional(() -> expected.cast(o))); if (opt.isPresent()) { return opt; } try { // should theoretically match any string -> object conversions, such as deser // for now im filtering against method names as well just to avoid issues where // expected result is not obtained due to weird methods, might change in future Method method = Arrays.stream(expected.getDeclaredMethods()) .filter(m -> Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) .filter(m -> Arrays.stream(m.getParameterTypes()).anyMatch(c -> c.equals(String.class))) .filter(m -> m.getReturnType().equals(expected) || m.getReturnType().equals(Optional.class)) .filter(m -> STRING_TO_VAL_PATTERN.matcher(m.getName()).find()).findAny().get(); // error if no Object valout = method.invoke(null, (String) val); if (valout == null) { return Optional.empty(); } if (expected.isInstance(valout)) { // Register a new deserializer once we confirm it works. Should prevent // extremely long parsing from happening multiple times. final MethodHandle mh = MethodHandles.publicLookup().unreflect(method); PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> { try { return expected.cast(mh.invokeExact((String) val)); } catch (Throwable e1) { throw new RuntimeException(e1); } }); return tryOptional(() -> expected.cast(valout)); } if (valout instanceof Optional) { Optional<?> valopt = (Optional<?>) valout; if (!valopt.isPresent()) { return Optional.empty(); } Object v = valopt.get(); if (expected.isInstance(v)) { // Register a new deserializer once we confirm it works. Should prevent // extremely long parsing from happening multiple times. final MethodHandle mh = MethodHandles.publicLookup().unreflect(method); PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> { try { Optional<?> optx = (Optional<?>) mh.invokeExact((String) val); return expected.cast(optx.get()); } catch (Throwable e1) { throw new RuntimeException(e1); } }); return tryOptional(() -> expected.cast(v)); } else { return Optional.empty(); } } return Optional.empty(); } catch (Exception e) { // fires if no method found, if invoke throws, if something else goes wrong return Optional.empty(); } } return TypeUtils.tryOptional(() -> expected.cast(val)); }
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 ww . j a va2 s . 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); } } } } }