List of usage examples for java.lang Class getDeclaredMethods
@CallerSensitive public Method[] getDeclaredMethods() throws SecurityException
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(); }/* www . j a v a 2s . co m*/ 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:gov.nih.nci.security.dao.AuthorizationDAOImpl.java
public Object secureUpdate(String userName, Object originalObject, Object mutatedObject) throws CSException { //Object o = null; if (StringUtilities.isBlank(userName)) { throw new CSException("No user name have been supplied!"); }//from w ww . java2 s. c o m if (originalObject == null || mutatedObject == null) { return originalObject; } try { Class cl = originalObject.getClass(); log.debug(cl.getName()); ObjectAccessMap accessMap = this.getObjectAccessMap(cl.getName(), userName, "UPDATE"); //o = cl.newInstance(); Method methods[] = cl.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; String name = m.getName(); log.debug("Method is: " + name); //log.debug("Name from outer block"+name); //log.debug("Para type"+m.getParameterTypes()); if (name.startsWith("set") && (m.getModifiers() == Modifier.PUBLIC)) { String att = name.substring(3, name.length()); log.debug("Attribute is: " + att); String methodName = "get" + att; //log.debug(methodName); Method m2 = cl.getMethod(methodName, (Class[]) null); //log.debug("Method Name m2"+m2.getName()); //log.debug(m2.invoke(obj,null)); if (!accessMap.hasAccess(att)) { log.debug("No Access to update attribute: " + att); Object origValue = m2.invoke(originalObject, (Object[]) null); if (origValue != null) { log.debug("Original value is: " + origValue.toString()); } m.invoke(mutatedObject, new Object[] { origValue }); } else { log.debug("Access permitted to update attribute: " + att); } } } } catch (Exception ex) { log.error("Error Securing object", ex); if (log.isDebugEnabled()) log.debug("Authorization||" + userName + "|secureUpdate|Failure|Error in Secure Update|" + ex.getMessage()); throw new CSException("Failed to secure update the object:" + ex.getMessage(), ex); } return mutatedObject; }
From source file:gov.nih.nci.security.dao.AuthorizationDAOImpl.java
public Object secureObject(String userName, Object obj) throws CSException { Object o = null;//w w w .jav a 2s.c o m if (StringUtilities.isBlank(userName)) { throw new CSException("No user name have been supplied!"); } if (obj == null) { return obj; } Field[] fields = obj.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getType().isPrimitive()) throw new CSException("The Object to be secured does not follow Java Bean Specification"); } try { Class cl = obj.getClass(); log.debug(cl.getName()); ObjectAccessMap accessMap = this.getObjectAccessMap(cl.getName(), userName, "READ"); log.debug(accessMap.toString()); o = cl.newInstance(); Method methods[] = cl.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; String name = m.getName(); //log.debug("Name from outer block"+name); //log.debug("Para type"+m.getParameterTypes()); if (name.startsWith("set") && (m.getModifiers() == Modifier.PUBLIC)) { String att = name.substring(3, name.length()); String methodName = "get" + att; //log.debug(methodName); Method m2 = cl.getMethod(methodName, (Class[]) null); //log.debug("Method Name m2"+m2.getName()); //log.debug(m2.invoke(obj,null)); if (!accessMap.hasAccess(att)) { m.invoke(o, new Object[] { null }); } else { m.invoke(o, new Object[] { m2.invoke(obj, (Object[]) null) }); } } } } catch (Exception ex) { if (log.isDebugEnabled()) log.debug("Authorization||" + userName + "|secureObject|Failure|Error in Secure Object|" + ex.getMessage()); throw new CSException("Failed to secure the object:" + ex.getMessage(), ex); } return o; }
From source file:gov.nih.nci.security.dao.AuthorizationDAOImpl.java
public Collection secureCollection(String userName, Collection collection) throws CSException { ArrayList result = new ArrayList(); if (collection.size() == 0) { return collection; }//from w ww . jav a 2s .co m if (StringUtilities.isBlank(userName)) { throw new CSException("No userName have been supplied!"); } try { Iterator it = collection.iterator(); List l = (List) collection; Object obj_ = (Object) l.get(0); Class cl = obj_.getClass(); log.debug(cl.getName()); ObjectAccessMap accessMap = this.getObjectAccessMap(cl.getName(), userName, "READ"); while (it.hasNext()) { Object obj = (Object) it.next(); Object o = cl.newInstance(); Method methods[] = cl.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; String name = m.getName(); //log.debug("Name from outer block"+name); //log.debug("Para type"+m.getParameterTypes()); if (name.startsWith("set") && (m.getModifiers() == Modifier.PUBLIC)) { String att = name.substring(3, name.length()); String methodName = "get" + att; //log.debug(methodName); Method m2 = cl.getMethod(methodName, (Class[]) null); //log.debug("Method Name m2"+m2.getName()); //log.debug(m2.invoke(obj,null)); if (!accessMap.hasAccess(att)) { m.invoke(o, new Object[] { null }); } else { m.invoke(o, new Object[] { m2.invoke(obj, (Object[]) null) }); } } } result.add(o); } } catch (Exception ex) { if (log.isDebugEnabled()) log.debug("Authorization||" + userName + "|secureCollection|Failure|Error in Secure Collection|" + ex.getMessage()); throw new CSException("Failed to secure Collection:" + ex.getMessage(), ex); } return result; }
From source file:ca.oson.json.Oson.java
private <T> void processMethods(Class<T> valueType, String fullName) { // Stream<Method> stream = Arrays.stream(valueType.getDeclaredMethods()); // while (valueType != null && valueType != Object.class) { // stream = Stream.concat(stream, Arrays.stream(valueType // .getSuperclass().getDeclaredMethods())); // valueType = (Class<T>) valueType.getSuperclass(); // }//ww w .j av a 2s. c o m Map<String, Method> setters = new LinkedHashMap<>(); Map<String, Method> getters = new LinkedHashMap<>(); Map<String, Method> others = new LinkedHashMap<>(); String name; boolean notSetGetOnly = !getSetGetOnly(); boolean completed = false; Class classType = valueType; int depth = 0; while (!completed && classType != null && classType != Object.class) { //for (Method method: stream.collect(Collectors.toList())) { for (Method method : classType.getDeclaredMethods()) { name = method.getName(); if (name.startsWith("set")) { if (name.length() > 3 && method.getParameterCount() == 1) { setters.put(name.substring(3).toLowerCase(), method); } else { others.put(name.toLowerCase(), method); } } else if (name.startsWith("get")) { if (name.length() > 3 && method.getParameterCount() == 0 && !void.class.equals(method.getReturnType())) { getters.put(name.substring(3).toLowerCase(), method); } else { others.put(name.toLowerCase(), method); } } else if (notSetGetOnly && method.getParameterCount() == 0 && !void.class.equals(method.getReturnType())) { getters.put(name.toLowerCase(), method); } else if (notSetGetOnly && method.getParameterCount() == 1) { setters.put(name.toLowerCase(), method); } else { others.put(name.toLowerCase(), method); } } if (depth > 1 && (getters.size() > 0 || setters.size() > 0)) { completed = true; } else { classType = classType.getSuperclass(); depth++; } } Map<String, Method>[] all = new HashMap[3]; all[METHOD.GET.value] = getters; all[METHOD.SET.value] = setters; all[METHOD.OTHER.value] = others; cachedMethods.put(fullName, all); }
From source file:ca.oson.json.Oson.java
private <T> T setSingleMapValue(T obj, Class<T> valueType, Object singleMapValue, Class singleMapValueType) { if (obj == null || valueType == null || singleMapValue == null || singleMapValueType == null) { return obj; }/*from w w w . j a v a 2s . co m*/ //check all methods // and invoke the right one // public static InetAddress getByName(String host) //Map<String, Method> setters = getSetters(valueType); for (Method method : valueType.getDeclaredMethods()) { if (method.getParameterCount() == 1) { if (ObjectUtil.isSameDataType(method.getParameterTypes()[0], singleMapValueType)) { Object object = ObjectUtil.getMethodValue(obj, method, singleMapValue); if (object != null && valueType.isAssignableFrom(object.getClass())) { return (T) object; } } } } return obj; }
From source file:ca.oson.json.Oson.java
private <E> String enum2Json(FieldData objectDTO) { Object value = objectDTO.valueToProcess; Class<E> valueType = objectDTO.returnType; EnumType enumType = objectDTO.getEnumType(); if (value == null) { return null; }/*from w w w . j a v a 2s . c om*/ Enum en = (Enum) value; try { Function function = objectDTO.getSerializer(); if (function != null) { try { if (function instanceof DataMapper2JsonFunction) { DataMapper classData = new DataMapper(objectDTO.returnType, value, objectDTO.classMapper, objectDTO.level, getPrettyIndentation()); return ((DataMapper2JsonFunction) function).apply(classData); } else if (function instanceof Enum2JsonFunction) { return ((Enum2JsonFunction) function).apply(en); } else { Object returnedValue = null; if (function instanceof FieldData2JsonFunction) { FieldData2JsonFunction f = (FieldData2JsonFunction) function; FieldData fieldData = objectDTO.clone(); returnedValue = f.apply(fieldData); } else { returnedValue = function.apply(value); } if (returnedValue instanceof Optional) { returnedValue = ObjectUtil.unwrap(returnedValue); } if (returnedValue == null) { return null; // just ignore it, right? } else if (Enum.class.isAssignableFrom(returnedValue.getClass())) { en = (Enum) returnedValue; } else { objectDTO.valueToProcess = returnedValue; return object2String(objectDTO); } } } catch (Exception e) { } } } catch (Exception ex) { } String name = en.name(); if (enumType == null || enumType == EnumType.STRING) { for (Method method : valueType.getDeclaredMethods()) { for (Annotation annotation : method.getDeclaredAnnotations()) { String aname = annotation.annotationType().getName(); switch (aname) { case "com.fasterxml.jackson.annotation.JsonValue": case "org.codehaus.jackson.annotate.JsonValue": return ObjectUtil.getMethodValue(en, method); case "ca.oson.json.annotation.FieldMapper": ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation; if (fieldMapper.jsonValue() != null && fieldMapper.jsonValue() == BOOLEAN.TRUE) { return ObjectUtil.getMethodValue(en, method); } } } } for (Field field : valueType.getDeclaredFields()) { if (name.equalsIgnoreCase(field.getName())) { ca.oson.json.annotation.FieldMapper fieldMapper = field .getAnnotation(ca.oson.json.annotation.FieldMapper.class); if (fieldMapper != null) { String aname = fieldMapper.name(); if (!StringUtil.isEmpty(aname)) { return aname; } } else { for (Annotation annotation : field.getAnnotations()) { String aname = ObjectUtil.getName(annotation); if (!StringUtil.isEmpty(aname)) { return aname; } } } } } return name; } switch (enumType) { case STRING: return en.name(); case ORDINAL: default: return "" + en.ordinal(); } }
From source file:ca.oson.json.Oson.java
private <E> Enum<?> json2Enum(FieldData objectDTO) { objectDTO.valueToProcess = StringUtil.unquote(objectDTO.valueToProcess, isEscapeHtml()); Object valueToProcess = objectDTO.valueToProcess; Class<E> returnType = objectDTO.returnType; boolean required = objectDTO.required(); Enum defaultValue = (Enum) objectDTO.defaultValue; boolean json2Java = objectDTO.json2Java; if (returnType == null || valueToProcess == null) { if (required) { return defaultValue; }//from w w w. j a v a 2 s . c o m return null; } String value = (String) valueToProcess; Class<Enum> enumType = (Class<Enum>) returnType; try { Function function = objectDTO.getDeserializer(); if (function != null) { Object returnedValue = null; if (function instanceof Json2DataMapperFunction) { DataMapper classData = new DataMapper(returnType, value, objectDTO.classMapper, objectDTO.level, getPrettyIndentation()); returnedValue = ((Json2DataMapperFunction) function).apply(classData); } else if (function instanceof Json2FieldDataFunction) { Json2FieldDataFunction f = (Json2FieldDataFunction) function; FieldData fieldData = objectDTO.clone(); returnedValue = f.apply(fieldData); } else if (function instanceof Json2EnumFunction) { return (Enum<?>) ((Json2EnumFunction) function).apply(value); } else { returnedValue = function.apply(value); } if (returnedValue instanceof Optional) { returnedValue = ObjectUtil.unwrap(returnedValue); } if (returnedValue == null) { return null; } Class type = returnedValue.getClass(); if (Enum.class.isAssignableFrom(type)) { return (Enum<?>) returnedValue; } else if (Number.class.isAssignableFrom(type)) { int ordinal = ((Number) returnedValue).intValue(); for (Enum enumValue : enumType.getEnumConstants()) { if (enumValue.ordinal() == ordinal) { return enumValue; } } } else { String name = returnedValue.toString(); for (Enum enumValue : enumType.getEnumConstants()) { if (enumValue.toString().equalsIgnoreCase(name) || enumValue.name().equalsIgnoreCase(name)) { return enumValue; } } } } } catch (Exception ex) { } for (Method method : enumType.getDeclaredMethods()) { for (Annotation annotation : method.getDeclaredAnnotations()) { String aname = annotation.annotationType().getName(); switch (aname) { case "com.fasterxml.jackson.annotation.JsonCreator": case "org.codehaus.jackson.annotate.JsonCreator": return ObjectUtil.getMethodValue(null, method, value); case "ca.oson.json.annotation.FieldMapper": ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation; if (fieldMapper.jsonCreator() != null && fieldMapper.jsonCreator() == BOOLEAN.TRUE) { return ObjectUtil.getMethodValue(null, method, value); } } } } String fieldName = null; for (Field field : enumType.getDeclaredFields()) { String name = null; ca.oson.json.annotation.FieldMapper fieldMapper = field .getAnnotation(ca.oson.json.annotation.FieldMapper.class); if (fieldMapper != null) { name = fieldMapper.name(); if (value.equalsIgnoreCase(name)) { fieldName = field.getName(); break; } } else { for (Annotation annotation : field.getAnnotations()) { name = ObjectUtil.getName(annotation); if (value.equalsIgnoreCase(name)) { fieldName = field.getName(); break; } } } } if (fieldName != null) { try { return Enum.valueOf(enumType, fieldName.toUpperCase()); } catch (IllegalArgumentException ex) { } } try { return Enum.valueOf(enumType, value.toUpperCase()); } catch (IllegalArgumentException ex) { } for (Enum enumValue : enumType.getEnumConstants()) { if (enumValue.toString().equalsIgnoreCase(value) || enumValue.name().equalsIgnoreCase(value)) { return enumValue; } } FieldData fieldData = new FieldData(value, Integer.class, true); Integer ordinal = json2Integer(fieldData); if (ordinal != null) { for (Enum enumValue : enumType.getEnumConstants()) { if (enumValue.ordinal() == ordinal) { return enumValue; } } } return null; }
From source file:ca.oson.json.Oson.java
<T> T newInstance(Map<String, Object> map, Class<T> valueType) { InstanceCreator creator = getTypeAdapter(valueType); if (creator != null) { return (T) creator.createInstance(valueType); }/*from w w w . j a v a 2 s .c o m*/ T obj = null; if (valueType != null) { obj = (T) getDefaultValue(valueType); if (obj != null) { return obj; } } if (map == null) { return null; } // @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = As.PROPERTY, property = "@class") //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class") String JsonClassType = null; if (valueType != null) { if (getAnnotationSupport()) { for (Annotation annotation : valueType.getAnnotations()) { if (annotation instanceof JsonTypeInfo) { JsonTypeInfo jsonTypeInfo = (JsonTypeInfo) annotation; JsonTypeInfo.Id use = jsonTypeInfo.use(); JsonTypeInfo.As as = jsonTypeInfo.include(); if ((use == JsonTypeInfo.Id.MINIMAL_CLASS || use == JsonTypeInfo.Id.CLASS) && as == As.PROPERTY) { JsonClassType = jsonTypeInfo.property(); } } } } } if (JsonClassType == null) { JsonClassType = getJsonClassType(); } String className = null; if (map.containsKey(JsonClassType)) { className = map.get(JsonClassType).toString(); } Class<T> classType = getClassType(className); // && (valueType == null || valueType.isAssignableFrom(classType) || Map.class.isAssignableFrom(valueType)) if (classType != null) { valueType = classType; } if (valueType == null) { return (T) map; // or null, which is better? } Constructor<?>[] constructors = null; Class implClass = null; if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) { implClass = DeSerializerUtil.implementingClass(valueType.getName()); } if (implClass != null) { constructors = implClass.getDeclaredConstructors(); } else { constructors = valueType.getDeclaredConstructors();//.getConstructors(); } Object singleMapValue = null; Class singleMapValueType = null; if (map.size() == 1) { singleMapValue = map.get(valueType.getName()); if (singleMapValue != null) { singleMapValueType = singleMapValue.getClass(); if (singleMapValueType == String.class) { singleMapValue = StringUtil.unquote(singleMapValue.toString(), isEscapeHtml()); } try { if (valueType == Locale.class) { Constructor constructor = null; String[] parts = ((String) singleMapValue).split("_"); if (parts.length == 1) { constructor = valueType.getConstructor(String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(singleMapValue); } else if (parts.length == 2) { constructor = valueType.getConstructor(String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } else if (parts.length == 3) { constructor = valueType.getConstructor(String.class, String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } if (obj != null) { return obj; } } } catch (Exception e) { } Map<Class, Constructor> cmaps = new HashMap<>(); for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount == 1) { Class[] types = constructor.getParameterTypes(); cmaps.put(types[0], constructor); } } if (cmaps.size() > 0) { Constructor constructor = null; if ((cmaps.containsKey(Boolean.class) || cmaps.containsKey(boolean.class)) && BooleanUtil.isBoolean(singleMapValue.toString())) { constructor = cmaps.get(Boolean.class); if (constructor == null) { constructor = cmaps.get(boolean.class); } if (constructor != null) { try { constructor.setAccessible(true); obj = (T) constructor .newInstance(BooleanUtil.string2Boolean(singleMapValue.toString())); if (obj != null) { return obj; } } catch (Exception e) { } } } else if (StringUtil.isNumeric(singleMapValue.toString())) { Class[] classes = new Class[] { int.class, Integer.class, long.class, Long.class, double.class, Double.class, Byte.class, byte.class, Short.class, short.class, Float.class, float.class, BigDecimal.class, BigInteger.class, AtomicInteger.class, AtomicLong.class, Number.class }; for (Class cls : classes) { constructor = cmaps.get(cls); if (constructor != null) { try { obj = (T) constructor.newInstance(NumberUtil.getNumber(singleMapValue, cls)); if (obj != null) { return obj; } } catch (Exception e) { } } } } else if (StringUtil.isArrayOrList(singleMapValue.toString()) || singleMapValue.getClass().isArray() || Collection.class.isAssignableFrom(singleMapValue.getClass())) { for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); if (cls.isArray() || Collection.class.isAssignableFrom(cls)) { Object listObject = null; if (singleMapValue instanceof String) { JSONArray objArray = new JSONArray(singleMapValue.toString()); listObject = (List) fromJsonMap(objArray); } else { listObject = singleMapValue; } FieldData objectDTO = new FieldData(listObject, cls, true); listObject = json2Object(objectDTO); if (listObject != null) { try { obj = (T) constructor.newInstance(listObject); if (obj != null) { return obj; } } catch (Exception e) { } } } } } for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); try { obj = (T) constructor.newInstance(singleMapValue); if (obj != null) { return obj; } } catch (Exception e) { } } } } } if (implClass != null) { valueType = implClass; } try { obj = valueType.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException e) { //e.printStackTrace(); } ///* for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Annotation[] annotations = constructor.getDeclaredAnnotations(); // getAnnotations(); for (Annotation annotation : annotations) { boolean isJsonCreator = false; if (annotation instanceof JsonCreator) { isJsonCreator = true; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation; if (fieldMapper.jsonCreator() == BOOLEAN.TRUE) { isJsonCreator = true; } } if (isJsonCreator) { Parameter[] parameters = constructor.getParameters(); String[] parameterNames = ObjectUtil.getParameterNames(parameters); //parameterCount = parameters.length; Object[] parameterValues = new Object[parameterCount]; int i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameters[i].getType()); i++; } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } else { try { constructor.setAccessible(true); obj = (T) constructor.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } //*/ // try again for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); try { List<String> parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null && parameterNames.size() > 0) { Class[] parameterTypes = constructor.getParameterTypes(); int length = parameterTypes.length; if (length == parameterNames.size()) { Object[] parameterValues = new Object[length]; Object parameterValue; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } catch (IOException e1) { // e1.printStackTrace(); } } } // try more for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Class[] parameterTypes = constructor.getParameterTypes(); List<String> parameterNames; try { parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null) { int length = parameterTypes.length; if (length > parameterNames.size()) { length = parameterNames.size(); } Object[] parameterValues = new Object[length]; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | IOException e) { //e.printStackTrace(); } } } // try more try { Method[] methods = valueType.getMethods(); // .getMethod("getInstance", null); List<Method> methodList = new ArrayList<>(); if (methods != null) { for (Method method : methods) { String methodName = method.getName(); if (methodName.equals("getInstance") || methodName.equals("newInstance") || methodName.equals("createInstance") || methodName.equals("factory")) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType) && Modifier.isStatic(method.getModifiers())) { int parameterCount = method.getParameterCount(); if (parameterCount == 0) { try { obj = ObjectUtil.getMethodValue(null, method); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } else { methodList.add(method); } } } } for (Method method : methodList) { try { int parameterCount = method.getParameterCount(); Object[] parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterCount == 1 && valueType != null && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(parameterTypes[0], singleMapValueType)) { try { obj = ObjectUtil.getMethodValue(null, method, singleMapValue); if (obj != null) { return obj; } } catch (IllegalArgumentException ex) { //ex.printStackTrace(); } } } else if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } obj = ObjectUtil.getMethodValue(null, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } catch (SecurityException e) { // e.printStackTrace(); } // try all static methods, if the return type is correct, get it as the final object Method[] methods = valueType.getDeclaredMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers())) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType)) { try { Object[] parameterValues = null; int parameterCount = method.getParameterCount(); if (parameterCount > 0) { if (parameterCount == 1 && map.size() == 1 && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(method.getParameterTypes()[0], singleMapValueType)) { obj = ObjectUtil.getMethodValue(null, method, singleMapValueType); if (obj != null) { return obj; } } } parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } } obj = ObjectUtil.getMethodValue(obj, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } return null; }