/** * Create object value instance. * * @param clazz object class. */ ObjectValue(Converter converter, Class<?> clazz) { this(converter); this.clazz = clazz; this.instance = Classes.newInstance(clazz); }
/** Create JSON value writer. */ public JsonValueWriter() { json = Classes.loadService(Json.class); }
/** * Construct parser collection with elements of given type. * * @param type collection elements type. */ CollectionValue(Converter converter, Type type) { this.converter = converter; if (!(type instanceof ParameterizedType)) { throw new JsonParserException("This JSON parser mandates generic collections usage but got |%s|.", type); } ParameterizedType parameterizedType = (ParameterizedType) type; this.instance = Classes.newCollection(parameterizedType.getRawType()); this.type = parameterizedType.getActualTypeArguments()[0]; }
/** * Create a new instance. Handy utility for hidden classes creation. Constructor accepting given arguments, if any, * must exists. * * @param className fully qualified class name, * @param arguments variable number of arguments to be passed to constructor. * @param <T> instance type. * @return newly created instance. * @throws NoSuchBeingException if class or constructor not found. */ @SuppressWarnings("unchecked") public static <T> T newInstance(String className, Object... arguments) { return (T)newInstance(Classes.forName(className), arguments); }
/** * Create an object instance of the requested type. If type is a {@link List} uses * {@link Classes#getListDefaultImplementation(Type)}. * * @param type object type. * @return newly created instance. */ public Object newInstance(Class<?> type) { if (Types.isKindOf(type, List.class)) { type = Classes.getListDefaultImplementation(type); } return Classes.newInstance(type); }
/** * Set instance field declared into superclass. Try to set field value throwing exception if field is not declared * into superclass; if field is static object instance should be null. * * @param object instance to set field value to or null if field is static, * @param clazz instance superclass where field is declared, * @param fieldName field name, * @param value field value. * @throws NoSuchBeingException if field not found. * @throws BugError if object is null and field is not static or if object is not null and field is static. */ public static void setFieldValue(Object object, Class<?> clazz, String fieldName, Object value) { Field field = getField(clazz, fieldName); if(object == null ^ Modifier.isStatic(field.getModifiers())) { throw new BugError("Cannot access static field |%s| from instance |%s|.", fieldName, clazz); } setFieldValue(object, field, value); }
if(rawClass.isInterface()) { if(Types.isCollection(rawClass)) { return newCollection(rawClass); return newMap(rawClass); return newInstance(t.getRawType(), arguments); return (T)newInstance((Class<?>)type, arguments);
Object object = Classes.newInstance(type); for (Parameter parameter : parameters) { Field field = Classes.getField(type, Strings.toMemberName(parameter.getName())); Classes.setFieldValue(object, field, asObject(parameter.getValue(), field.getType()));
/** * Get class or superclass named field with checked exception. Tries to get requested field from given class; if not * found try with superclass, if any. If both attempts fail throw {@link NoSuchFieldException}. * * @param clazz class to search for named field, * @param fieldName the name of field to retrieve. * @return requested field. * @throws NoSuchFieldException if class or superclass has no field with requested name. */ public static Field getFieldEx(Class<?> clazz, String fieldName) throws NoSuchFieldException { try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch(NoSuchFieldException e) { Class<?> superclass = clazz.getSuperclass(); if(superclass != null && clazz.getPackage().equals(superclass.getPackage())) { return getFieldEx(superclass, fieldName); } throw e; } catch(SecurityException e) { throw new BugError(e); } }
List<String> values = Strings.split(valuesString, ','); Field field = getField(object.getClass(), fieldName); Type type = field.getType(); Object instance = null; instance = newCollection(type); for(int i = 0; i < values.size(); i++) { ((Collection<Object>)instance).add(converter.asObject(values.get(i), componentType)); setFieldValue(object, field, instance);
Class<?> pojoClass = Classes.forOptionalName(pojoClassName); if (pojoClass == null) { throw new ConfigException("Missing configured POJO class |%s|.", pojoClassName); Field staticField = Classes.getOptionalField(pojoClass, fieldName); if (staticField == null) { throw new ConfigException("Missing POJO static field |%s#%s|.", pojoClassName, fieldName); Classes.setFieldValue(null, staticField, value);
/** * Load service of requested interface using given class loader. Throws exception if service implementation not found * on run-time. * * @param serviceInterface service interface, * @param classLoader class loader. * @param <S> service type. * @return service instance. * @throws NoProviderException if service provider not found on run-time. */ public static <S> S loadService(Class<S> serviceInterface, ClassLoader classLoader) { Iterator<S> services = ServiceLoader.load(serviceInterface, classLoader).iterator(); if(services.hasNext()) { return services.next(); } // although not official, Android does not support ServiceLoader // there is no way to insert service descriptor files into apk META-INF // as an workaround uses a hard coded 'services' package to store service descriptors try { String serviceDescriptor = getResourceAsString("/services/" + serviceInterface.getName()); return newInstance(serviceDescriptor); } catch(Throwable e) { // log.dump("Service not found", e); } return null; }
if (Classes.isInstantiable(type)) { return Classes.newInstance(type);
Class<?>[] parameterTypes = getParameterTypes(arguments); try { Method method = clazz.getDeclaredMethod(methodName, parameterTypes); return (T)invoke(object, method, arguments); return (T)invoke(object, method, arguments);
/** * Convenient method to retrieve named resource as reader. Uses {@link #getResourceAsStream(String)} and return the * stream wrapped into a reader. * * @param name resource name. * @return reader for named resource. * @throws UnsupportedEncodingException if Java run-time does not support UTF-8 encoding. * @throws NoSuchBeingException if resource not found. */ public static Reader getResourceAsReader(String name) throws UnsupportedEncodingException { return new InputStreamReader(getResourceAsStream(name), "UTF-8"); }
throw new NullPointerException("Null class name."); Class<T> clazz = forOptionalName(className); if(clazz == null) { throw new NoSuchBeingException("Class not found: " + className);
Field field = Classes.getOptionalField(implementationClass, fieldName); if (field == null) { throw new ConfigException("Missing managed class static field |%s#%s|.", implementationClass, fieldName); Classes.setFieldValue(null, field, config.getAttribute("value", field.getType()));
Class<?> implementation = Classes.forOptionalName(className); if (implementation == null) { throw new ConfigException("Unable to load view implementation |%s|.", className); throw new ConfigException("View implementation |%s| is not of proper type.", className); if (!Classes.isInstantiable(implementation)) { throw new ConfigException("View implementation |%s| is not instantiable. Ensure is not abstract or interface and have default constructor.", implementation);
/** * Return the Java class instance for given canonical name. If given string is empty returns null. If class not found warn * to logger and also returns null. */ @Override public <T> T asObject(String string, Class<T> valueType) { // at this point value type is a class if (string.isEmpty()) return null; // uses this library Classes#forName instead of Java standard Class#forName // first uses current thread context loader whereas the second uses library loader // as a consequence classes defined by web app could not be found if use Java standard Class#forName try { return (T) Classes.forName(string); } catch (NoSuchBeingException e) { log.warn("Class |%s| not found. Class converter force return value to null.", string); return null; } }
/** * Get the type of named field or null if field does not exist. * * @return field type or null. */ public Type getValueType() { Field field = Classes.getOptionalField(clazz, fieldName); return field != null ? field.getGenericType() : null; }