List of usage examples for java.lang Class isArray
@HotSpotIntrinsicCandidate public native boolean isArray();
From source file:com.discovery.darchrow.lang.ClassUtil.java
/** * class info map for LOGGER./*from www . j ava2 s.com*/ * * @param klass * the clz * @return the map for log */ public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) { if (Validator.isNullOrEmpty(klass)) { return null; } Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("clz.getCanonicalName()", klass.getCanonicalName());//"com.feilong.core.date.DatePattern" map.put("clz.getName()", klass.getName());//"com.feilong.core.date.DatePattern" map.put("clz.getSimpleName()", klass.getSimpleName());//"DatePattern" map.put("clz.getComponentType()", klass.getComponentType()); // ?? voidboolean?byte?char?short?int?long?float double? map.put("clz.isPrimitive()", klass.isPrimitive()); // ??, map.put("clz.isLocalClass()", klass.isLocalClass()); // ????,?????? map.put("clz.isMemberClass()", klass.isMemberClass()); //isSynthetic()?Class????java??false?trueJVM???java?????? map.put("clz.isSynthetic()", klass.isSynthetic()); map.put("clz.isArray()", klass.isArray()); map.put("clz.isAnnotation()", klass.isAnnotation()); //??true map.put("clz.isAnonymousClass()", klass.isAnonymousClass()); map.put("clz.isEnum()", klass.isEnum()); return map; }
From source file:com.avalara.avatax.services.base.ser.BeanDeserializer.java
/** * Get the Deserializer for the attribute or child element. * @param xmlType QName of the attribute/child element or null if not known. * @param javaType Class of the corresponding property * @param href String is the value of the href attribute, which is used * to determine whether the child element is complete or an * href to another element./* w w w . jav a 2 s.c o m*/ * @param context DeserializationContext * @return Deserializer or null if not found. */ protected Deserializer getDeserializer(QName xmlType, Class javaType, String href, DeserializationContext context) { if (javaType.isArray()) { context.setDestinationClass(javaType); } // See if we have a cached deserializer if (cacheStringDSer != null) { if (String.class.equals(javaType) && href == null && (cacheXMLType == null && xmlType == null || cacheXMLType != null && cacheXMLType.equals(xmlType))) { cacheStringDSer.reset(); return cacheStringDSer; } } Deserializer dSer = null; if (xmlType != null && href == null) { // Use the xmlType to get the deserializer. dSer = context.getDeserializerForType(xmlType); } else { // If the xmlType is not set, get a default xmlType TypeMapping tm = context.getTypeMapping(); QName defaultXMLType = tm.getTypeQName(javaType); // If there is not href, then get the deserializer // using the javaType and default XMLType, // If there is an href, the create the generic // DeserializerImpl and set its default type (the // default type is used if the href'd element does // not have an xsi:type. if (href == null) { dSer = context.getDeserializer(javaType, defaultXMLType); } else { dSer = new DeserializerImpl(); context.setDestinationClass(javaType); dSer.setDefaultType(defaultXMLType); } } if (javaType.equals(String.class) && dSer instanceof SimpleDeserializer) { cacheStringDSer = (SimpleDeserializer) dSer; cacheXMLType = xmlType; } return dSer; }
From source file:com.medallia.spider.api.DynamicInputImpl.java
private static Object parseSingleValue(Class<?> rt, String v, AnnotatedElement anno, Map<Class<?>, InputArgParser<?>> inputArgParsers) { if (rt.isEnum()) { String vlow = v.toLowerCase(); for (Enum e : rt.asSubclass(Enum.class).getEnumConstants()) { if (e.name().toLowerCase().equals(vlow)) return e; }/*from www . j a va 2s .c om*/ throw new AssertionError("Enum constant not found: " + v); } else if (rt == Integer.class) { // map blank strings to null return Strings.hasContent(v) ? Integer.valueOf(v) : null; } else if (rt == Integer.TYPE) { // primitive int must have a value return Integer.valueOf(v); } else if (rt == Long.class) { // map blank strings to null return Strings.hasContent(v) ? Long.valueOf(v) : null; } else if (rt == Long.TYPE) { // primitive long must have a value return Long.valueOf(v); } else if (rt == Double.class) { // map blank strings to null return Strings.hasContent(v) ? Double.valueOf(v) : null; } else if (rt == Double.TYPE) { // primitive double must have a value return Double.valueOf(v); } else if (rt == String.class) { return v; } else if (rt.isArray()) { Input.List ann = anno.getAnnotation(Input.List.class); if (ann == null) throw new AssertionError("Array type but no annotation (see " + Input.class + "): " + anno); String separator = ann.separator(); String[] strVals = v.split(separator, -1); Class<?> arrayType = rt.getComponentType(); Object a = Array.newInstance(arrayType, strVals.length); for (int i = 0; i < strVals.length; i++) { Array.set(a, i, parseSingleValue(arrayType, strVals[i], anno, inputArgParsers)); } return a; } else if (inputArgParsers != null) { InputArgParser<?> argParser = inputArgParsers.get(rt); if (argParser != null) { return argParser.parse(v); } } throw new AssertionError("Unknown return type " + rt + " (val: " + v + ")"); }
From source file:io.s4.util.LoadGenerator.java
@SuppressWarnings("unchecked") private Object makeSettableValue(Property property, Object value) { String propertyName = property.getName(); Class propertyType = property.getType(); if (propertyType.isArray()) { if (!(value instanceof JSONArray)) { System.err.println("Type mismatch for field " + propertyName); return null; }/*from w w w. j ava 2 s .c om*/ System.out.println("Is array!"); return makeArray(property, (JSONArray) value); } else if (property.isList()) { if (!(value instanceof JSONArray)) { System.err.println("Type mismatch for field " + propertyName); return null; } return makeList(property, (JSONArray) value); } else if (propertyType.isPrimitive()) { if (!(value instanceof Number || value instanceof Boolean)) { System.err.println("Type mismatch for field " + propertyName + "; expected number or boolean, found " + value.getClass()); return null; } return value; // hmm... does this work? } else if (propertyType.equals(String.class)) { if (!(value instanceof String)) { System.err.println( "Type mismatch for field " + propertyName + "; expected String, found " + value.getClass()); return null; } return value; } else if (property.isNumber()) { if (!(value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof BigDecimal || value instanceof BigInteger)) { return null; } Number adjustedValue = (Number) value; if (propertyType.equals(Long.class) && !(value instanceof Long)) { adjustedValue = new Long(((Number) value).longValue()); } else if (propertyType.equals(Integer.class) && !(value instanceof Integer)) { adjustedValue = new Integer(((Number) value).intValue()); } else if (propertyType.equals(Double.class) && !(value instanceof Double)) { adjustedValue = new Double(((Number) value).doubleValue()); } else if (propertyType.equals(Float.class) && !(value instanceof Float)) { adjustedValue = new Float(((Number) value).floatValue()); } else if (propertyType.equals(BigDecimal.class)) { adjustedValue = new BigDecimal(((Number) value).longValue()); } else if (propertyType.equals(BigInteger.class)) { adjustedValue = BigInteger.valueOf(((Number) value).longValue()); } return adjustedValue; } else if (value instanceof JSONObject) { return makeRecord((JSONObject) value, property.getSchema()); } return null; }
From source file:info.magnolia.content2bean.impl.TypeMappingImpl.java
@Override public TypeDescriptor getTypeDescriptor(Class<?> beanClass) { TypeDescriptor dscr = types.get(beanClass); // eh, we know about this type, don't bother resolving any further. if (dscr != null) { return dscr; }/*from w ww . j av a 2 s .c o m*/ dscr = new TypeDescriptor(); dscr.setType(beanClass); dscr.setMap(Map.class.isAssignableFrom(beanClass)); dscr.setCollection(beanClass.isArray() || Collection.class.isAssignableFrom(beanClass)); types.put(beanClass, dscr); if (!beanClass.isArray() && !beanClass.isPrimitive()) { // don't bother looking for a transformer if the property is an array or a primitive type Content2BeanTransformer transformer = null; // TODO ? transformerProvider.getTransformerFor(beanClass); try { if (transformer == null) { transformer = findTransformerByNamingConvention(beanClass); } if (transformer == null) { transformer = findTransformerViaProperty(beanClass); } } catch (Exception e) { // this is fine because having a transformer class is optional log.debug("No custom transformer class {}Transformer class found", beanClass.getName()); } dscr.setTransformer(transformer); } return dscr; }
From source file:com.zenesis.qx.remote.ProxyMethod.java
/** * @param name//from ww w .jav a2 s .c o m * @param returnType * @param parameters */ public ProxyMethod(Method method) { super(); this.method = method; Class returnType = method.getReturnType(); Class keyType = String.class; boolean prefetchResult = false; boolean cacheResult = false; isMap = Map.class.isAssignableFrom(returnType); com.zenesis.qx.remote.annotations.Method anno = method .getAnnotation(com.zenesis.qx.remote.annotations.Method.class); if (returnType.isArray() || Iterable.class.isAssignableFrom(returnType) || isMap) { // How to present on the client - only ArrayList by default is wrapped on the client Remote.Array array; if (returnType.isArray()) { returnType = returnType.getComponentType(); array = Remote.Array.NATIVE; } else { returnType = Object.class; array = Remote.Array.WRAP; } // Component type if (anno != null) { if (anno.array() != Remote.Array.DEFAULT) array = anno.array(); if (anno.arrayType() != Object.class) returnType = anno.arrayType(); if (anno.keyType() != Object.class) keyType = anno.keyType(); } this.array = array; this.arrayType = returnType; } else { array = null; this.arrayType = null; } if (anno != null) { if (method.getParameterTypes().length == 0) { prefetchResult = anno.prefetchResult(); cacheResult = anno.cacheResult() || prefetchResult; } } this.keyType = keyType; this.prefetchResult = prefetchResult; this.staticMethod = (method.getModifiers() & Modifier.STATIC) != 0; if (staticMethod && cacheResult) { log.warn("Cannot cacheResult on static method " + method); cacheResult = false; } this.cacheResult = cacheResult; }
From source file:javadz.beanutils.locale.LocaleConvertUtilsBean.java
/** * Convert an array of specified values to an array of objects of the * specified class (if possible) using the convertion pattern. * * @param values Value to be converted (may be null) * @param clazz Java array or element class to be converted to * @param locale The locale// ww w. ja v a 2 s .c o m * @param pattern The convertion pattern * @return the converted value * * @throws org.apache.commons.beanutils.ConversionException if thrown by an * underlying Converter */ public Object convert(String[] values, Class clazz, Locale locale, String pattern) { Class type = clazz; if (clazz.isArray()) { type = clazz.getComponentType(); } if (log.isDebugEnabled()) { log.debug("Convert String[" + values.length + "] to class " + type.getName() + "[] using " + locale + " locale and " + pattern + " pattern"); } Object array = Array.newInstance(type, values.length); for (int i = 0; i < values.length; i++) { Array.set(array, i, convert(values[i], type, locale, pattern)); } return (array); }
From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.NativeArrayConverter.java
/** * {@inheritDoc}/*w ww .j a v a 2s . c om*/ */ @Override public Object convertValueForJava(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass) { if (!(value instanceof NativeArray)) { throw new IllegalArgumentException("value must be a NativeArray"); } final NativeArray arr = (NativeArray) value; final Object[] ids = arr.getIds(); final Object result; if (expectedClass.isAssignableFrom(List.class) || expectedClass.isArray()) { final Class<?> expectedComponentClass = expectedClass.isArray() ? expectedClass.getComponentType() : Object.class; final List<Object> list = new ArrayList<Object>(); for (int idx = 0; idx < ids.length; idx++) { if (ids[idx] instanceof Integer) { final Object element = arr.get(((Integer) ids[idx]).intValue(), arr); final Object converted = globalDelegate.convertValueForJava(element, expectedComponentClass); list.add(converted); } } if (expectedClass.isArray()) { final Object newArr = Array.newInstance(expectedComponentClass, list.size()); for (int idx = 0; idx < list.size(); idx++) { Array.set(newArr, idx, list.get(idx)); } result = newArr; } else { result = list; } } else { final Map<Object, Object> propValues = new HashMap<Object, Object>(ids.length); for (final Object propId : ids) { final Object val = arr.get(propId.toString(), arr); final Object convertedKey = globalDelegate.convertValueForJava(propId); final Object convertedValue = globalDelegate.convertValueForJava(val); propValues.put(convertedKey, convertedValue); } result = propValues; } return result; }
From source file:com.basistech.rosette.apimodel.ModelTest.java
private Object createObjectForType(Class<?> type, Type genericParameterType) throws IllegalAccessException, InstantiationException, InvocationTargetException { Object o = null;//w w w .j a v a 2 s . c om Class firstComponentType = type.isArray() ? type.getComponentType() : type; String typeName = firstComponentType.getSimpleName(); Class parameterArgClass = null; Type[] parameterArgTypes = null; if (genericParameterType != null) { if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; parameterArgTypes = aType.getActualTypeArguments(); for (Type parameterArgType : parameterArgTypes) { if (parameterArgType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) parameterArgType; if (isListString(parameterizedType)) { List<List<String>> rv = Lists.newArrayList(); rv.add(Lists.newArrayList("string")); return rv; } } else { parameterArgClass = (Class) parameterArgType; if ("Map".equals(typeName)) { break; } } } } } if (firstComponentType.isEnum()) { return firstComponentType.getEnumConstants()[0]; } switch (typeName) { case "byte": { if (type.isArray()) { o = "somebytes".getBytes(); } else { o = (byte) '8'; } break; } case "String": case "CharSequence": { o = "foo"; break; } case "long": case "Long": { o = (long) 123456789; break; } case "Double": case "double": { o = 1.0; break; } case "int": case "Integer": { o = 98761234; break; } case "boolean": case "Boolean": { o = false; break; } case "Collection": case "List": { if (parameterArgClass != null) { Object o1 = createObjectForType(parameterArgClass, null); List<Object> list = new ArrayList<>(); list.add(o1); o = list; } break; } case "Object": if (inputStreams) { o = new ByteArrayInputStream(new byte[0]); } else { o = "foo"; } break; case "EnumSet": break; case "Set": { if (parameterArgClass != null) { Object o1 = createObjectForType(parameterArgClass, null); Set<Object> set = new HashSet<>(); set.add(o1); o = set; } break; } case "Map": { if (parameterArgTypes != null && parameterArgTypes.length == 2) { Class keyClass = (Class) parameterArgTypes[0]; Object keyObject = createObject(keyClass); if (keyObject != null) { HashMap<Object, Object> map = new HashMap<>(); map.put(keyObject, null); o = map; } } break; } default: if (parameterArgClass != null) { Constructor[] ctors = parameterArgClass.getDeclaredConstructors(); o = createObject(ctors[0]); } else { Constructor[] ctors = firstComponentType.getDeclaredConstructors(); o = createObject(ctors[0]); } } return o; }
From source file:com.alibaba.dubbo.governance.web.common.module.screen.Restful.java
public void execute(Map<String, Object> context) throws Throwable { if (context.get(WebConstants.CURRENT_USER_KEY) != null) { User user = (User) context.get(WebConstants.CURRENT_USER_KEY); currentUser = user;//from w w w . ja va2 s . com operator = user.getUsername(); role = user.getRole(); context.put(WebConstants.CURRENT_USER_KEY, user); } operatorAddress = (String) context.get("request.remoteHost"); context.put("operator", operator); context.put("operatorAddress", operatorAddress); context.put("currentRegistry", currentRegistry); String httpMethod = (String) context.get("request.method"); String method = (String) context.get("_method"); String contextPath = (String) context.get("request.contextPath"); context.put("rootContextPath", new RootContextPath(contextPath)); // ?Method if (method == null || method.length() == 0) { String id = (String) context.get("id"); if (id == null || id.length() == 0) { method = "index"; } else { method = "show"; } } if ("index".equals(method)) { if ("post".equalsIgnoreCase(httpMethod)) { method = "create"; } } else if ("show".equals(method)) { if ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // ????PUTPOST method = "update"; } else if ("delete".equalsIgnoreCase(httpMethod)) { // ????DELETE? method = "delete"; } } context.put("_method", method); try { Method m = null; try { m = getClass().getMethod(method, new Class<?>[] { Map.class }); } catch (NoSuchMethodException e) { for (Method mtd : getClass().getMethods()) { if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().equals(method)) { m = mtd; break; } } if (m == null) { throw e; } } if (m.getParameterTypes().length > 2) { throw new IllegalStateException("Unsupport restful method " + m); } else if (m.getParameterTypes().length == 2 && (m.getParameterTypes()[0].equals(Map.class) || !m.getParameterTypes()[1].equals(Map.class))) { throw new IllegalStateException("Unsupport restful method " + m); } Object r; if (m.getParameterTypes().length == 0) { r = m.invoke(this, new Object[0]); } else { Object value; Class<?> t = m.getParameterTypes()[0]; if (Map.class.equals(t)) { value = context; } else if (isPrimitive(t)) { String id = (String) context.get("id"); value = convertPrimitive(t, id); } else if (t.isArray() && isPrimitive(t.getComponentType())) { String id = (String) context.get("id"); String[] ids = id == null ? new String[0] : id.split("[.+]+"); value = Array.newInstance(t.getComponentType(), ids.length); for (int i = 0; i < ids.length; i++) { Array.set(value, i, convertPrimitive(t.getComponentType(), ids[i])); } } else { value = t.newInstance(); for (Method mtd : t.getMethods()) { if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().startsWith("set") && mtd.getParameterTypes().length == 1) { String p = mtd.getName().substring(3, 4).toLowerCase() + mtd.getName().substring(4); Object v = context.get(p); if (v == null) { if ("operator".equals(p)) { v = operator; } else if ("operatorAddress".equals(p)) { v = (String) context.get("request.remoteHost"); } } if (v != null) { try { mtd.invoke(value, new Object[] { CompatibleTypeUtils.compatibleTypeConvert(v, mtd.getParameterTypes()[0]) }); } catch (Throwable e) { logger.warn(e.getMessage(), e); } } } } } if (m.getParameterTypes().length == 1) { r = m.invoke(this, new Object[] { value }); } else { r = m.invoke(this, new Object[] { value, context }); } } if (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class) { context.put("rundata.layout", "redirect"); context.put("rundata.target", "redirect"); context.put("success", r == null || ((Boolean) r).booleanValue()); if (context.get("redirect") == null) { context.put("redirect", getDefaultRedirect(context, method)); } } else if (m.getReturnType() == String.class) { String redirect = (String) r; if (redirect == null) { redirect = getDefaultRedirect(context, method); } if (context.get("chain") != null) { context.put("rundata.layout", "home"); context.put("rundata.target", "home"); } else { context.put("rundata.redirect", redirect); } } else { context.put("rundata.layout", method); context.put("rundata.target", context.get("rundata.target") + "/" + method); } } catch (Throwable e) { if (e instanceof InvocationTargetException) { throw ((InvocationTargetException) e).getTargetException(); } // if (e instanceof InvocationTargetException) { // e = ((InvocationTargetException) e).getTargetException(); // } // logger.warn(e.getMessage(), e); // context.put("rundata.layout", "redirect"); // context.put("rundata.target", "redirect"); // context.put("success", false); // context.put("exception", e); // context.put("redirect", getDefaultRedirect(context, method)); } }