List of usage examples for java.lang.reflect Type toString
public String toString()
From source file:com.github.hateoas.forms.spring.SpringActionDescriptor.java
private boolean containsCollection(final Type genericReturnType) { final boolean ret; if (genericReturnType instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) genericReturnType; Type rawType = t.getRawType(); Assert.state(rawType instanceof Class<?>, "raw type is not a Class: " + rawType.toString()); Class<?> cls = (Class<?>) rawType; if (HttpEntity.class.isAssignableFrom(cls)) { Type[] typeArguments = t.getActualTypeArguments(); ret = containsCollection(typeArguments[0]); } else if (Resources.class.isAssignableFrom(cls) || Collection.class.isAssignableFrom(cls)) { ret = true;//w ww . jav a 2 s . co m } else { ret = false; } } else if (genericReturnType instanceof GenericArrayType) { ret = true; } else if (genericReturnType instanceof WildcardType) { WildcardType t = (WildcardType) genericReturnType; ret = containsCollection(getBound(t.getLowerBounds())) || containsCollection(getBound(t.getUpperBounds())); } else if (genericReturnType instanceof TypeVariable) { ret = false; } else if (genericReturnType instanceof Class) { Class<?> cls = (Class<?>) genericReturnType; ret = Resources.class.isAssignableFrom(cls) || Collection.class.isAssignableFrom(cls); } else { ret = false; } return ret; }
From source file:org.j2free.admin.ReflectionMarshaller.java
private ReflectionMarshaller(Class klass) throws Exception { instructions = new HashMap<Field, Converter>(); LinkedList<Field> fieldsToMarshall = new LinkedList<Field>(); // Only marshallOut entities if (!klass.isAnnotationPresent(Entity.class)) throw new Exception("Provided class is not an @Entity"); // Add the declared fields fieldsToMarshall.addAll(Arrays.asList(klass.getDeclaredFields())); /* Inheritence support * Continue up the inheritance ladder until: * - There are no more super classes (zuper == null), or * - The super class is not an @Entity *///w ww. j a va2s .c om Class zuper = klass; while ((zuper = zuper.getSuperclass()) != null) { // get out if we find a super class that isn't an @Entity if (!klass.isAnnotationPresent(Entity.class)) break; // Add the declared fields // @todo, improve the inheritance support, the current way will overwrite // overridden fields in subclasses with the super class's field fieldsToMarshall.addAll(Arrays.asList(zuper.getDeclaredFields())); } /* By now, fieldsToMarshall should contain all the fields * so it's time to figure out how to access them. */ Method getter, setter; Converter converter; for (Field field : fieldsToMarshall) { int mod = field.getModifiers(); if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { log.debug("Skipping final or static field " + field.getName()); continue; } getter = setter = null; // if direct access doesn't work, look for JavaBean // getters and setters String fieldName = field.getName(); Class fieldType = field.getType(); try { getter = getGetter(field); } catch (NoSuchMethodException nsme) { log.debug("Failed to find getter for " + fieldName); } try { setter = getSetter(field); } catch (NoSuchMethodException nsme) { log.debug("Failed to find setter for " + fieldName); } if (getter == null && setter == null) { // Shit, we didn't figure out how to access it log.debug("Could not access field: " + field.getName()); } else { converter = new Converter(getter, setter); if (field.isAnnotationPresent(Id.class)) { log.debug("Found entityIdFied for " + klass.getName() + ": " + field.getName()); entityIdField = field; embeddedId = false; } if (field.isAnnotationPresent(EmbeddedId.class)) { log.debug("Found embedded entityIdFied for " + klass.getName() + ": " + field.getName()); entityIdField = field; embeddedId = true; } if (field.isAnnotationPresent(GeneratedValue.class) || setter == null) { converter.setReadOnly(true); } if (field.getType().isAnnotationPresent(Entity.class)) { converter.setEntity(fieldType); } Class superClass = field.getType(); if (superClass != null) { do { if (superClass == Collection.class) { try { Type type = field.getGenericType(); String typeString = type.toString(); while (typeString.matches("[^<]+?<[^>]+?>")) typeString = typeString.substring(typeString.indexOf("<") + 1, typeString.indexOf(">")); Class collectionType = Class.forName(typeString); converter.setCollection(collectionType); if (collectionType.getAnnotation(Entity.class) != null) converter.setEntity(collectionType); log.debug(field.getName() + " is entity = " + converter.isEntity()); log.debug(field.getName() + " collectionType = " + converter.getType().getSimpleName()); } catch (Exception e) { log.debug("error getting collection type", e); } finally { break; } } superClass = superClass.getSuperclass(); } while (superClass != null); } instructions.put(field, converter); } } }
From source file:au.com.addstar.cellblock.configuration.AutoConfig.java
public boolean save() { try {/* ww w . ja v a 2 s .c om*/ onPreSave(); YamlConfiguration config = new YamlConfiguration(); Map<String, String> comments = new HashMap<>(); // Add all the category comments comments.putAll(mCategoryComments); // Add all the values for (Field field : getClass().getDeclaredFields()) { ConfigField configField = field.getAnnotation(ConfigField.class); if (configField == null) continue; String optionName = configField.name(); if (optionName.isEmpty()) optionName = field.getName(); field.setAccessible(true); String path = (configField.category().isEmpty() ? "" : configField.category() + ".") + optionName; //$NON-NLS-2$ // Ensure the secion exists if (!configField.category().isEmpty() && !config.contains(configField.category())) config.createSection(configField.category()); if (field.getType().isArray()) { // Integer if (field.getType().getComponentType().equals(Integer.TYPE)) config.set(path, Arrays.asList((Integer[]) field.get(this))); // Float else if (field.getType().getComponentType().equals(Float.TYPE)) config.set(path, Arrays.asList((Float[]) field.get(this))); // Double else if (field.getType().getComponentType().equals(Double.TYPE)) config.set(path, Arrays.asList((Double[]) field.get(this))); // Long else if (field.getType().getComponentType().equals(Long.TYPE)) config.set(path, Arrays.asList((Long[]) field.get(this))); // Short else if (field.getType().getComponentType().equals(Short.TYPE)) config.set(path, Arrays.asList((Short[]) field.get(this))); // Boolean else if (field.getType().getComponentType().equals(Boolean.TYPE)) config.set(path, Arrays.asList((Boolean[]) field.get(this))); // String else if (field.getType().getComponentType().equals(String.class)) config.set(path, Arrays.asList((String[]) field.get(this))); else throw new IllegalArgumentException( "Cannot use type " + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-2$ } else if (List.class.isAssignableFrom(field.getType())) { if (field.getGenericType() == null) throw new IllegalArgumentException( "Cannot use type List without specifying generic type for AutoConfiguration"); Type type = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; if (type.equals(Integer.class) || type.equals(Float.class) || type.equals(Double.class) || type.equals(Long.class) || type.equals(Short.class) || type.equals(Boolean.class) || type.equals(String.class)) { config.set(path, field.get(this)); } else throw new IllegalArgumentException("Cannot use type " + field.getType().getSimpleName() + "<" + type.toString() + "> for AutoConfiguration"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (Set.class.isAssignableFrom(field.getType())) { if (field.getGenericType() == null) throw new IllegalArgumentException( "Cannot use type Set without specifying generic type for AutoConfiguration"); Type type = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; if (type.equals(Integer.class) || type.equals(Float.class) || type.equals(Double.class) || type.equals(Long.class) || type.equals(Short.class) || type.equals(Boolean.class) || type.equals(String.class)) { config.set(path, new ArrayList<Object>((Set<?>) field.get(this))); } else throw new IllegalArgumentException("Cannot use type " + field.getType().getSimpleName() + "<" + type.toString() + "> for AutoConfiguration"); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Integer if (field.getType().equals(Integer.TYPE)) config.set(path, field.get(this)); // Float else if (field.getType().equals(Float.TYPE)) config.set(path, field.get(this)); // Double else if (field.getType().equals(Double.TYPE)) config.set(path, field.get(this)); // Long else if (field.getType().equals(Long.TYPE)) config.set(path, field.get(this)); // Short else if (field.getType().equals(Short.TYPE)) config.set(path, field.get(this)); // Boolean else if (field.getType().equals(Boolean.TYPE)) config.set(path, field.get(this)); // ItemStack else if (field.getType().equals(ItemStack.class)) config.set(path, field.get(this)); // String else if (field.getType().equals(String.class)) config.set(path, field.get(this)); else throw new IllegalArgumentException( "Cannot use type " + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-2$ } // Record the comment if (!configField.comment().isEmpty()) comments.put(path, configField.comment()); } String output = config.saveToString(); // Apply comments String category = ""; List<String> lines = new ArrayList<>(Arrays.asList(output.split("\n"))); for (int l = 0; l < lines.size(); l++) { String line = lines.get(l); if (line.startsWith("#")) continue; if (line.trim().startsWith("-")) continue; if (!line.contains(":")) continue; String path; line = line.substring(0, line.indexOf(":")); if (line.startsWith(" ")) path = category + "." + line.substring(2).trim(); else { category = line.trim(); path = line.trim(); } if (comments.containsKey(path)) { String indent = ""; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == ' ') indent += " "; else break; } // Add in the comment lines String[] commentLines = comments.get(path).split("\n"); lines.add(l++, ""); for (int i = 0; i < commentLines.length; i++) { commentLines[i] = indent + "# " + commentLines[i]; lines.add(l++, commentLines[i]); } } } output = ""; for (String line : lines) output += line + "\n"; FileWriter writer = new FileWriter(mFile); writer.write(output); writer.close(); return true; } catch (IllegalArgumentException | IOException | IllegalAccessException e) { e.printStackTrace(); } return false; }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
private String getHeirarchyStr(List<Type> fheirlst) { StringBuilder b = new StringBuilder(); if (!fheirlst.isEmpty()) { for (Type type : fheirlst) { b.append(type.toString() + "."); }/* w w w.j ava 2 s . c o m*/ } return b.toString(); }
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
/** * @param method/*www . j a v a2s. c om*/ * @return */ protected String getReturnType(final Method method) { Class<?> classObj = method.getReturnType(); // If there is a better way, PLEASE help me! if (classObj == Set.class) { ParameterizedType type = (ParameterizedType) method.getGenericReturnType(); for (Type t : type.getActualTypeArguments()) { String cls = t.toString(); return cls.substring(6, cls.length()); } } return classObj.getName(); }
From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java
private static String getExceptionMessage(String resourceKey, Method[] methods, Type[] requiredTypes, Type[] exactTypes, Type[] optionalTypes, Type returnType) { MethodInfo methodInfo = getMethodInfo(methods); StringBuffer sb = new StringBuffer(); for (int i = 0; i < requiredTypes.length; i++) { if (i > 0) { sb.append(","); }/*from www. j a v a 2s . co m*/ Type argType = requiredTypes[i]; if (argType != null) { sb.append(getClassName(argType)); } else { sb.append("*"); } } String required = sb.toString(); sb.setLength(0); for (int i = 0; i < exactTypes.length; i++) { if (i > 0) { sb.append(","); } Type argType = exactTypes[i]; if (argType != null) { sb.append(getClassName(argType)); } else { sb.append("*"); } } String exact = sb.toString(); sb.setLength(0); for (int i = 0; i < optionalTypes.length; i++) { if (i > 0) { sb.append(","); } Type argType = optionalTypes[i]; if (argType != null) { sb.append(getClassName(argType)); } else { sb.append("*"); } } String optional = sb.toString(); return resourceManager.getString(resourceKey, methodInfo.getClassName(), methodInfo.getMethodName(), required, exact, optional, ((returnType != null) ? returnType.toString() : "*")); }
From source file:io.swagger.client.ApiClient.java
/** * Deserialize response body to Java object, according to the return type and * the Content-Type response header./*from ww w . j ava2s.com*/ * * @param <T> Type * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ @SuppressWarnings("unchecked") public <T> T deserialize(Response response, Type returnType) throws ApiException, IOException { if (response == null || returnType == null) { return null; } if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). try { return (T) response.body().bytes(); } catch (IOException e) { throw new ApiException(e); } } else if (returnType.equals(File.class)) { // Handle file downloading. return (T) downloadFileFromResponse(response); } String respBody; try { if (response.body() != null) respBody = response.body().string(); else respBody = null; } catch (IOException e) { throw new ApiException(e); } if (respBody == null || "".equals(respBody)) { return null; } String contentType = response.headers().get("Content-Type"); if (contentType == null) { // ensuring a default content type contentType = "application/json"; } else if (contentType.equals("application/xml")) { if (XML.toJSONObject(respBody).has("TaskList")) { JSONObject rootElement = (JSONObject) XML.toJSONObject(respBody).get("TaskList"); return this.json.deserialize( ((JSONArray) ((JSONObject) rootElement.get("Tasks")).get("Tasks")).toString(), returnType); } } if (isJsonMime(contentType)) { if (new JSONObject(respBody).has("Tasks")) { return json.deserialize(new JSONObject(respBody).get("Tasks").toString(), returnType); } else { return json.deserialize(respBody, returnType); } } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. return (T) respBody; } else { throw new ApiException("Content type \"" + contentType + "\" is not supported for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); } }
From source file:org.ocelotds.core.services.ArgumentConvertor.java
/** * try to convert json argument in java type * * @param arg/*w w w . j a va2s. c o m*/ * @param paramType * @return * @throws IllegalArgumentException */ Object convertArgument(String arg, Type paramType) throws IllegalArgumentException { Object result = null; if (null == arg || "null".equals(arg)) { return result; } logger.debug("Try to convert {} : param = {} : {}", new Object[] { arg, paramType, paramType.getClass() }); try { // GenericArrayType, ParameterizedType, TypeVariable<D>, WildcardType, Class if (ParameterizedType.class.isInstance(paramType)) { JavaType javaType = getJavaType(paramType); logger.debug("Try to convert '{}'to JavaType : '{}'", arg, paramType); result = getObjectMapper().readValue(arg, javaType); logger.debug("Conversion of '{}'to '{}' : OK", arg, paramType); } else if (Class.class.isInstance(paramType)) { Class cls = (Class) paramType; logger.debug("Try to convert '{}' to Class '{}'", arg, paramType); checkStringArgument(cls, arg); result = getObjectMapper().readValue(arg, cls); logger.debug("Conversion of '{}'to '{}' : OK", arg, paramType); } else { // GenericArrayType, TypeVariable<D>, WildcardType logger.warn("Conversion of '{}'to '{}' not yet supported", arg, paramType); } } catch (IOException ex) { logger.debug("Conversion of '{}' to '{}' failed", arg, paramType); throw new IllegalArgumentException(paramType.toString()); } return result; }
From source file:com.clarkparsia.empire.annotation.RdfGenerator.java
private static Class refineClass(final Object theAccessor, final Class theClass, final DataSource theSource, final Resource theId) { Class aClass = theClass;//from www .j a v a 2 s . c om if (Collection.class.isAssignableFrom(aClass)) { // if the field we're assigning from is a collection, try and figure out the type of the thing // we're creating from the collection Type[] aTypes = null; if (theAccessor instanceof Field && ((Field) theAccessor).getGenericType() instanceof ParameterizedType) { aTypes = ((ParameterizedType) ((Field) theAccessor).getGenericType()).getActualTypeArguments(); } else if (theAccessor instanceof Method) { aTypes = ((Method) theAccessor).getGenericParameterTypes(); } if (aTypes != null && aTypes.length >= 1) { // first type argument to a collection is usually the one we care most about if (aTypes[0] instanceof ParameterizedType && ((ParameterizedType) aTypes[0]).getActualTypeArguments().length > 0) { Type aType = ((ParameterizedType) aTypes[0]).getActualTypeArguments()[0]; if (aType instanceof Class) { aClass = (Class) aType; } else if (aType instanceof WildcardTypeImpl) { WildcardTypeImpl aWildcard = (WildcardTypeImpl) aType; // trying to suss out super v extends w/o resorting to string munging. if (aWildcard.getLowerBounds().length == 0 && aWildcard.getUpperBounds().length > 0) { // no lower bounds afaik indicates ? extends Foo aClass = ((Class) aWildcard.getUpperBounds()[0]); } else if (aWildcard.getLowerBounds().length > 0) { // lower & upper bounds I believe indicates something of the form Foo super Bar aClass = ((Class) aWildcard.getLowerBounds()[0]); } else { // shoot, we'll try the string hack that Adrian posted on the mailing list. try { aClass = Class.forName(aType.toString().split(" ")[2].substring(0, aTypes[0].toString().split(" ")[2].length() - 1)); } catch (Exception e) { // everything has failed, let aClass be the default (theClass) and hope for the best } } } else { // punt? wtf else could it be? try { aClass = Class.forName(aType.toString()); } catch (ClassNotFoundException e) { // oh well, we did the best we can } } } else if (aTypes[0] instanceof Class) { aClass = (Class) aTypes[0]; } } else { // could not figure out the type from the generics assertions on the Collection, they are either // not present, or my algorithm is not bullet proof. So lets try checking on the annotations // for a type hint. Class aTarget = BeanReflectUtil.getTargetEntity(theAccessor); if (aTarget != null) { aClass = aTarget; } } } if (!BeanReflectUtil.hasAnnotation(aClass, RdfsClass.class) || aClass.isInterface()) { // k, so either the parameter of the collection or the declared type of the field does // not map to an instance/bean type. this is most likely an error, but lets try and find // the rdf:type of the field, and see if we can map that to a class in the path and we'll // create an instance of that. that will work, and pushes the likely failure back off to // the assignment of the created instance Iterable<Resource> aTypes = DataSourceUtil.getTypes(theSource, theId); // k, so now we know the type, if we can match the type to a class then we're in business for (Resource aType : aTypes) { if (aType instanceof URI) { for (Class aTypeClass : TYPE_TO_CLASS.get((URI) aType)) { if ((BeanReflectUtil.hasAnnotation(aTypeClass, RdfsClass.class)) && (aClass.isAssignableFrom(aTypeClass))) { // lets try this one aClass = aTypeClass; break; } } } } } if (aClass.isInterface()) { if (BeanReflectUtil.hasAnnotation(aClass, RdfsClass.class)) { URI aType = FACTORY.createURI(((RdfsClass) aClass.getAnnotation(RdfsClass.class)).value()); for (Class aTypeClass : TYPE_TO_CLASS.get(aType)) { if ((BeanReflectUtil.hasAnnotation(aTypeClass, RdfsClass.class)) && (aClass.isAssignableFrom(aTypeClass))) { // lets try this one aClass = aTypeClass; return aClass; } } } } return aClass; }
From source file:org.apache.sling.models.impl.ModelAdapterFactory.java
/** * Injects the default initial value for the given primitive class which * cannot be null (e.g. int = 0, boolean = false). * // w w w .ja v a2s . co m * @param point Annotated element * @param callback Inject callback */ private RuntimeException injectPrimitiveInitialValue(InjectableElement point, InjectCallback callback) { Type primitiveType = ReflectionUtil.mapWrapperClasses(point.getType()); Object value = null; if (primitiveType == int.class) { value = 0; } else if (primitiveType == long.class) { value = 0L; } else if (primitiveType == boolean.class) { value = Boolean.FALSE; } else if (primitiveType == double.class) { value = 0.0d; } else if (primitiveType == float.class) { value = 0.0f; } else if (primitiveType == short.class) { value = (short) 0; } else if (primitiveType == byte.class) { value = (byte) 0; } else if (primitiveType == char.class) { value = '\u0000'; } if (value != null) { return callback.inject(point, value); } else { return new ModelClassException(String.format("Unknown primitive type %s", primitiveType.toString())); } }