/** * Infer value type in one collection type * * @param genericType * @return */ public static Type inferElementTypeIn(Type collectionType) { if (collectionType instanceof Class) { return Object.class; } else if (collectionType instanceof ParameterizedType) { ParameterizedType parameterizedCollectionType = (ParameterizedType) collectionType; Type collectionValueType = parameterizedCollectionType.getActualTypeArguments()[0]; if (collectionValueType instanceof Class) { return (Class) collectionValueType; } else if (collectionValueType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) collectionValueType; return type.getRawType(); } else if (collectionValueType instanceof WildcardType) { throw new UnusableTypeException( "we can't infer element type in widlcard type " + collectionType.toString()); } else if (collectionValueType instanceof TypeVariable) { throw new UnusableTypeException( "we can't infer element type in type variable " + collectionType.toString()); } } else if (collectionType instanceof WildcardType) { throw new UnusableTypeException( "we can't infer element type in widlcard type " + collectionType.toString()); } else if (collectionType instanceof TypeVariable) { throw new UnusableTypeException( "we can't infer element type in type variable " + collectionType.toString()); } throw new UnusableTypeException("we can't infer element type in " + collectionType.toString()); }
public Object inject(InjectionContext context) { if (injectionProvider == null) { return null; } Object injectedValue; try { injectedValue = injectionProvider.provideInjection(context); } catch (InjectionProviderException e) { Throwable ex = e; if (ex.getCause() != null) { ex = ex.getCause(); } String message = "InjectionProvider unable to resolve @" + injectionAnnotation.annotationType().getSimpleName() + " " + injectionType.toString(); throw new ConstructionException(message, ex); } if (injectedValue == null && !optional) { String message = "Non-optional @" + injectionAnnotation.annotationType().getSimpleName() + " " + injectionType.toString() + " was null in " + injectedClass.getName(); throw new ConstructionException(message); } return getInjectedValue(injectedValue); }
public String toString() { StringBuilder sb = new StringBuilder(); if (ownerType != null) { if (ownerType instanceof Class) sb.append(((Class) ownerType).getName()); else sb.append(ownerType.toString()); sb.append("."); if (ownerType instanceof ParameterizedTypeImpl) { // Find simple name of nested type by removing the // shared prefix with owner. sb.append( rawType .getName() .replace(((ParameterizedTypeImpl) ownerType).rawType.getName() + "$", "")); } else sb.append(rawType.getName()); } else sb.append(rawType.getName()); if (actualTypeArguments != null && actualTypeArguments.length > 0) { sb.append("<"); boolean first = true; for (Type t : actualTypeArguments) { if (!first) sb.append(", "); if (t instanceof Class) sb.append(((Class) t).getName()); else sb.append(t.toString()); first = false; } sb.append(">"); } return sb.toString(); }
public static void main(String[]argv) throws Exception { Method m = Goo.class.getDeclaredMethod("getStrings"); Type t = m.getGenericReturnType(); if (!t.toString().equals("java.util.List<java.lang.String>")) throw new RuntimeException("Incorrect signature. Signature is "+t); m = IFace.class.getDeclaredMethod("getStrings"); t = m.getGenericReturnType(); if (!t.toString().equals("java.util.List<java.lang.String>")) throw new RuntimeException("Incorrect signature. Signature is "+t); }
@Override public T deserialize(final JsonElement je, final Type type, final JsonDeserializationContext jdc) throws JsonParseException { // Get the "content" element from the parsed JSON JsonElement content = je; if (je.isJsonObject() && je.getAsJsonObject().has("contents")) { content = je.getAsJsonObject().get("contents"); final int lastIndex = type.toString().lastIndexOf('.'); final String name = type.toString().substring(lastIndex + 1).toLowerCase(); if (content.isJsonObject() && content.getAsJsonObject().has(name)) { content = content.getAsJsonObject().get(name); } } return new Gson().fromJson(content, type); }
/** * Factory method that can be used if type information is passed as Java typing returned from * <code>getGenericXxx</code> methods (usually for a return or argument type). */ public JavaType _fromType(Type type, TypeBindings context) { // simple class? if (type instanceof Class<?>) { Class<?> cls = (Class<?>) type; /* 24-Mar-2010, tatu: Better create context if one was not passed; * mostly matters for root serialization types */ if (context == null) { context = new TypeBindings(cls); } return _fromClass(cls, context); } // But if not, need to start resolving. if (type instanceof ParameterizedType) { return _fromParamType((ParameterizedType) type, context); } if (type instanceof GenericArrayType) { return _fromArrayType((GenericArrayType) type, context); } if (type instanceof TypeVariable<?>) { return _fromVariable((TypeVariable<?>) type, context); } if (type instanceof WildcardType) { return _fromWildcard((WildcardType) type, context); } // sanity check throw new IllegalArgumentException("Unrecognized Type: " + type.toString()); }
public void testBindsGenericsToSuperclassEnvironment() throws SecurityException, NoSuchMethodException { TypeEnvironmentFactory env = new TypeEnvironmentFactory(); Type type = Grandpa.class.getMethod("returnsGeneric", new Class[0]).getGenericReturnType(); Type asSeenFromGrandpa = env.getEnvironment(Grandpa.class).bind(type); assertTrue(asSeenFromGrandpa instanceof TypeVariable); assertEquals("T", asSeenFromGrandpa.toString()); Type asSeenFromDad = env.getEnvironment(Dad.class).bind(type); assertTrue(asSeenFromDad instanceof ParameterizedType); assertEquals("java.util.List<T>", asSeenFromDad.toString()); ParameterizedType asSeenFromSon = (ParameterizedType) env.getEnvironment(Son.class).bind(type); assertType_isCollectionOfClass_withElementsOfClass(asSeenFromSon, List.class, String.class); }
@SuppressWarnings("rawtypes") protected Class getClassAtDepth(Type type, int depth) throws Exception { if (depth <= 0) { String className = type.toString(); if (className.length() >= 6 && className.substring(0, 6).equalsIgnoreCase("class ")) { className = className.substring(6); } if (className.indexOf("<") >= 0) { className = className.substring(0, className.indexOf("<")); } try { return Class.forName(className); } catch (ClassNotFoundException ex) { // ugly fix for primitive data types if (className.equalsIgnoreCase("byte")) return Byte.class; if (className.equalsIgnoreCase("short")) return Short.class; if (className.equalsIgnoreCase("int")) return Integer.class; if (className.equalsIgnoreCase("long")) return Long.class; if (className.equalsIgnoreCase("float")) return Float.class; if (className.equalsIgnoreCase("double")) return Double.class; if (className.equalsIgnoreCase("char")) return Character.class; if (className.equalsIgnoreCase("boolean")) return Boolean.class; throw ex; } } depth--; ParameterizedType pType = (ParameterizedType) type; Type[] typeArgs = pType.getActualTypeArguments(); return getClassAtDepth(typeArgs[typeArgs.length - 1], depth); }
public <T> Class<T> inferValueClassForListOrSet(Type genericType, Class<?> entityClass) { log.debug( "Infer parameterized value class for collection type {} of entity class {} ", genericType.toString(), entityClass.getCanonicalName()); Class<T> valueClass; if (genericType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericType; Type[] actualTypeArguments = pt.getActualTypeArguments(); if (actualTypeArguments.length > 0) { Type type = actualTypeArguments[actualTypeArguments.length - 1]; valueClass = getClassFromType(type); } else { throw new AchillesBeanMappingException( "The type '" + genericType.getClass().getCanonicalName() + "' of the entity '" + entityClass.getCanonicalName() + "' should be parameterized"); } } else { throw new AchillesBeanMappingException( "The type '" + genericType.getClass().getCanonicalName() + "' of the entity '" + entityClass.getCanonicalName() + "' should be parameterized"); } log.trace("Inferred value class : {}", valueClass.getCanonicalName()); return valueClass; }
/** Returns the most elemental class associated with {@link genericType} May return null */ public static Class<?> classFromType(Type genericType) { Class<?> defKlass; if (genericType == null) { return null; } if (genericType instanceof Class<?>) { defKlass = (Class<?>) genericType; } else if (genericType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericType; Type typeArgs[] = pt.getActualTypeArguments(); if (typeArgs.length != 1) { // Odd - better to ignore this return null; } return classFromType(typeArgs[0]); } else if (genericType instanceof GenericArrayType) { GenericArrayType gat = (GenericArrayType) genericType; defKlass = gat.getGenericComponentType().getClass(); } else if (genericType instanceof TypeVariable<?>) { TypeVariable<?> tv = (TypeVariable<?>) genericType; defKlass = tv.getClass(); } else { LOG.debug("classFromType unknown instance type [" + genericType.toString() + "] - ignoring"); defKlass = null; } return defKlass; }
@Override public String toString() { StringBuilder b = new StringBuilder(); for (Class<?> ann : annotations) { b.append(ann.getSimpleName()).append(' '); } b.append((type instanceof Class<?>) ? ((Class<?>) type).getSimpleName() : type.toString()); return b.toString(); }
/** * This helper class is used to find the class name from Type. This may not be reliable. * * @param genericType * @return */ private String getClassName(Type genericType) { String name = genericType.toString(); if (name == null || name.length() == 0) return DatabaseObject.class.getSimpleName(); // Use the top-most name if (name.endsWith(">")) { int index = name.lastIndexOf("."); if (index > 0) return name.substring(index + 1, name.length() - 1); } return DatabaseObject.class.getSimpleName(); // Use as the default }
/** * Convert the type into a string. The string representation approximates the code that would be * used to define the type. * * @param type - the type. * @return a string representation of the type, similar to how it was declared. */ public static String toString(Type type) { if (type instanceof ParameterizedType) return toString((ParameterizedType) type); if (type instanceof WildcardType) return toString((WildcardType) type); if (type instanceof GenericArrayType) return toString((GenericArrayType) type); if (type instanceof Class) { final Class theClass = (Class) type; return (theClass.isArray() ? theClass.getName() + "[]" : theClass.getName()); } return type.toString(); }
public static <X> String createParameterId(Type type, Set<Annotation> annotations) { StringBuilder builder = new StringBuilder(); if (type instanceof Class<?>) { Class<?> c = (Class<?>) type; builder.append(c.getName()); } else { builder.append(type.toString()); } builder.append(createAnnotationCollectionId(annotations)); return builder.toString(); }
/** * 获取一个类的某个一个泛型参数 * * @param klass 类 * @param index 参数下标 (从 0 开始) * @return 泛型参数类型 */ @SuppressWarnings("unchecked") public static <T> Class<T> getTypeParam(Class<?> klass, int index) { Type[] types = getTypeParams(klass); if (index >= 0 && index < types.length) { Type t = types[index]; Class<T> clazz = (Class<T>) Lang.getTypeClass(t); if (clazz == null) throw Lang.makeThrow("Type '%s' is not a Class", t.toString()); return clazz; } throw Lang.makeThrow("Class type param out of range %d/%d", index, types.length); }
public static void main(String... args) { try { Class<?> c = Class.forName(args[0]); out.format("Class:%n %s%n%n", c.getCanonicalName()); out.format("Modifiers:%n %s%n%n", Modifier.toString(c.getModifiers())); out.format("Type Parameters:%n"); TypeVariable<?>[] tv = c.getTypeParameters(); if (tv.length != 0) { out.format(" "); for (TypeVariable<?> t : tv) out.format("%s ", t.getName()); out.format("%n%n"); } else { out.format(" -- No Type Parameters --%n%n"); } out.format("Implemented Interfaces:%n"); Type[] intfs = c.getGenericInterfaces(); if (intfs.length != 0) { for (Type intf : intfs) out.format(" %s%n", intf.toString()); out.format("%n"); } else { out.format(" -- No Implemented Interfaces --%n%n"); } out.format("Inheritance Path:%n"); List<Class<?>> l = new ArrayList<Class<?>>(); printAncestor(c, l); if (l.size() != 0) { for (Class<?> cl : l) out.format(" %s%n", cl.getCanonicalName()); out.format("%n"); } else { out.format(" -- No Super Classes --%n%n"); } out.format("Annotations:%n"); Annotation[] ann = c.getAnnotations(); if (ann.length != 0) { for (Annotation a : ann) out.format(" %s%n", a.toString()); out.format("%n"); } else { out.format(" -- No Annotations --%n%n"); } // production code should handle this exception more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } }
private static Class getClass(Type type) { if (type instanceof Class) { return (Class) type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType() instanceof Class) { return (Class) parameterizedType.getRawType(); } } throw new IllegalArgumentException( "Type parameter [" + type.toString() + "] not a class or " + "parameterized type whose raw type is a class"); }
private Class<?> getGenericSubtype(Class<?> clazz, Type t) { if (!(clazz.getName().equals("void") || t.toString().equals("void"))) { try { ParameterizedType paramType = (ParameterizedType) t; Type[] argTypes = paramType.getActualTypeArguments(); if (argTypes.length > 0) { Class<?> c = (Class<?>) argTypes[0]; return c; } } catch (ClassCastException e) { // FIXME: find out why this happens to only certain types } } return clazz; }
/** * Deserialize response body to Java object, according to the return type and the Content-Type * response header. * * @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 { 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"; } if (isJsonMime(contentType)) { 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); } }
/** * @param annotationType The annotation type. * @param validators List of constraint validator classes (for a given constraint). * @param <A> the type of the annotation * @return Return a Map<Class, Class<? extends ConstraintValidator>> where the map key * is the type the validator accepts and value the validator class itself. */ public static <A extends Annotation> Map<Type, Class<? extends ConstraintValidator<A, ?>>> getValidatorsTypes( Class<A> annotationType, List<Class<? extends ConstraintValidator<A, ?>>> validators) { Map<Type, Class<? extends ConstraintValidator<A, ?>>> validatorsTypes = newHashMap(); for (Class<? extends ConstraintValidator<A, ?>> validator : validators) { Type type = extractType(validator); if (validatorsTypes.containsKey(type)) { throw log.getMultipleValidatorsForSameTypeException( annotationType.getName(), type.toString()); } validatorsTypes.put(type, validator); } return validatorsTypes; }
private static AssertionError buildUnexpectedTypeError(Type token, Class<?>... expected) { // Build exception message StringBuilder exceptionMessage = new StringBuilder("Unexpected type. Expected one of: "); for (Class<?> clazz : expected) { exceptionMessage.append(clazz.getName()).append(", "); } exceptionMessage .append("but got: ") .append(token.getClass().getName()) .append(", for type token: ") .append(token.toString()) .append('.'); return new AssertionError(exceptionMessage.toString()); }
/** Try to find the best matching service */ @Override @SuppressWarnings("unchecked") public FinderCrudService<?, Informer<?>> get(Type type) { if (type instanceof Class) { return get((Class) type); } else if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type raw = pType.getRawType(); if (raw instanceof Class) { Class rawClass = (Class) raw; if (Collection.class.isAssignableFrom(rawClass)) { return get(pType.getActualTypeArguments()[0]); } } } throw new NoSuchServiceException( "class " + type.toString() + " appears as not managed by a service of this repository"); }
/** 将Map<String,Object>转换为实体类(测试一次通过,待继续测试) */ public static <T> T castEntity(Class<T> c, Map<String, Object> map) throws Exception { T t = c.newInstance(); Field[] field = c.getDeclaredFields(); for (Field f : field) { Type type = f.getType(); String fieldname = f.getName(); for (String key : map.keySet()) { if (fieldname.toLowerCase().equals(key.toLowerCase())) { Method m = t.getClass().getDeclaredMethod("set" + initcap(fieldname), (Class<?>) type); if (m != null) { if ("class java.lang.String".equals(type.toString())) { m.invoke(t, map.get(key).toString()); } else { m.invoke(t, map.get(key)); } } break; } } } return t; }
/** Checks all fields in test class for compliance with the API xml. */ @SuppressWarnings("unchecked") private void checkFieldsCompliance() { for (JDiffField field : jDiffFields) { try { Field f = findMatchingField(field); if (f == null) { mResultObserver.notifyFailure( SignatureTestActivity.FAILURE_TYPE.MISSING_FIELD, field.toReadableString(mAbsoluteClassName), "No field with correct signature found:" + field.toSignatureString()); } else if (f.getModifiers() != field.mModifier) { mResultObserver.notifyFailure( SignatureTestActivity.FAILURE_TYPE.MISMATCH_FIELD, field.toReadableString(mAbsoluteClassName), "Non-compatible field modifiers found when looking for " + field.toSignatureString()); } else if (!f.getType().getCanonicalName().equals(field.mFieldType)) { // type name does not match, but this might be a generic String genericTypeName = null; Type type = f.getGenericType(); if (type != null) { genericTypeName = type instanceof Class ? ((Class) type).getName() : type.toString(); } if (genericTypeName == null || !genericTypeName.equals(field.mFieldType)) { mResultObserver.notifyFailure( SignatureTestActivity.FAILURE_TYPE.MISMATCH_FIELD, field.toReadableString(mAbsoluteClassName), "Non-compatible field type found when looking for " + field.toSignatureString()); } } } catch (Exception e) { SignatureTestLog.e("Got exception when checking field compliance", e); mResultObserver.notifyFailure( SignatureTestActivity.FAILURE_TYPE.CAUGHT_EXCEPTION, field.toReadableString(mAbsoluteClassName), "Exception!"); } } }
private Class<?> findConcreteType( Type generic, Class<?> resource, Map<String, Type> parametersMap) throws ClassNotFoundException { for (Type superInterface : resource.getGenericInterfaces()) { if (superInterface instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType) superInterface; Class<?> clazz = Class.forName( p.getRawType() .toString() .substring(p.getRawType().toString().lastIndexOf(' ') + 1)); Map<String, Type> map = new HashMap<>(); for (int i = 0; i < p.getActualTypeArguments().length; i++) { if (!map.containsKey(clazz.getTypeParameters()[i].toString())) { map.put(clazz.getTypeParameters()[i].toString(), p.getActualTypeArguments()[i]); } } if (map.containsKey(generic.toString())) { String type = map.get(generic.toString()).toString(); try { Class<?> returnClass = Class.forName(type.substring(type.lastIndexOf(' ') + 1)); return returnClass; } catch (ClassNotFoundException e) { break; } } } } if (parametersMap.containsKey(generic.toString())) { try { Type type = parametersMap.get(generic.toString()); Class<?> returnClass = Class.forName(type.toString().substring(type.toString().indexOf(' ') + 1)); return returnClass; } catch (ClassNotFoundException e) { return null; } } else { return null; } }
/** * オブジェクトのメソッドを呼び出す * * @param Object o メソッドを呼び出したいオブジェクト * @param String methodName 呼び出したいメソッドの名前 * @param Object... args メソッドのパラメータ * @throws NoSuchMethodException */ public static Object invoke(Object o, String methodName, Object... args) throws SecurityException, ClassNotFoundException, NoSuchMethodException { StringBuffer tempMessage = new StringBuffer(); Method method = null; // //argsArray:メソッドの引数の型配列 // Class<?>[] argsArray = new Class<?>[args.length]; // for(int i = 0; i < args.length; i++){ // argsArray[i] = getClassObject(args[i]); // //スーパークラスを引数にとれるように修正 // } // try { // method = o.getClass().getMethod(methodName, argsArray); // } catch (NoSuchMethodException e) { // try{ // method = o.getClass().getDeclaredMethod(methodName, argsArray); // }catch (NoSuchMethodException e2) { // message = "NoSuchMethodException\r\n"; // display.append(message); // } // } ///////////////////////////////////////// // argsArray:メソッドの引数の型配列 Class<?>[] argsArray = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { argsArray[i] = getClassObject(args[i]); } method = getMethod(o, args, methodName, argsArray); //////////////////////////////////////// tempMessage.append("method: " + method.getName() + " is called.\r\n"); if (Modifier.isPrivate(method.getModifiers())) { method.setAccessible(true); } if (o.equals(null)) { if (Modifier.isStatic(method.getModifiers()) == false) { throw new NoSuchMethodException(); } } try { Type returnType = method.getGenericReturnType(); tempMessage.append("return type: " + returnType.toString() + "\r\n"); if (returnType.equals(Void.TYPE)) { tempMessage.append("return value: " + "なし\r\n"); } else { tempMessage.append("return value: " + method.invoke(o, args).toString() + "\r\n"); } message = tempMessage.toString(); display.append(message); return method.invoke(o, args); } catch (IllegalArgumentException e) { e.printStackTrace(); message = tempMessage.append("IllegalArgumentException\r\n").toString(); display.append(message); } catch (IllegalAccessException e) { e.printStackTrace(); message = tempMessage.append("IllegalAccessException\r\n").toString(); display.append(message); } catch (InvocationTargetException e) { e.printStackTrace(); tempMessage.append("InvocationTargetException\r\n"); message = tempMessage.append(e.getCause().toString() + "\r\n").toString(); display.append(message); } return null; }
/** * Returns a string representation of this object. * * @return a string representation of this object. */ @Override public String toString() { return type instanceof Class<?> ? ((Class<?>) type).getName() : type.toString(); }
public static String typeToString(Type type) { return type instanceof Class ? ((Class<?>) type).getName() : type.toString(); }
/** * Create an Aegis type from a reflected type description. This will only work for the restricted * set of collection types supported by Aegis. * * @param t the reflected type. * @return the type */ public AegisType createType(Type t) { TypeClassInfo info = new TypeClassInfo(); info.setType(t); info.setDescription("reflected type " + t.toString()); return createTypeForClass(info); }
/** For debugging use only. */ @Override public String toString() { return domainObject.toString() + " => " + requestedType.toString(); }