List of usage examples for java.lang Class equals
public boolean equals(Object obj)
From source file:com.evolveum.midpoint.prism.xml.XmlTypeConverter.java
public static <T> List<T> convertValueElementAsList(Element valueElement, Class<T> type) throws SchemaException { if (type.equals(Object.class)) { if (DOMUtil.hasXsiType(valueElement)) { Object scalarValue = convertValueElementAsScalar(valueElement, DOMUtil.resolveXsiType(valueElement)); List<Object> list = new ArrayList<Object>(1); list.add(scalarValue);// w w w . j av a 2s . c o m return (List<T>) list; } } return convertValueElementAsList(valueElement.getChildNodes(), type); }
From source file:com.mawujun.util.AnnotationUtils.java
/** * <p>Checks if two annotations are equal using the criteria for equality * presented in the {@link Annotation#equals(Object)} API docs.</p> * * @param a1 the first Annotation to compare, {@code null} returns * {@code false} unless both are {@code null} * @param a2 the second Annotation to compare, {@code null} returns * {@code false} unless both are {@code null} * @return {@code true} if the two annotations are {@code equal} or both * {@code null}//from w ww . java2 s .co m */ public static boolean equals(Annotation a1, Annotation a2) { if (a1 == a2) { return true; } if (a1 == null || a2 == null) { return false; } Class<? extends Annotation> type = a1.annotationType(); Class<? extends Annotation> type2 = a2.annotationType(); Validate.notNull(type, "Annotation %s with null annotationType()", a1); Validate.notNull(type2, "Annotation %s with null annotationType()", a2); if (!type.equals(type2)) { return false; } try { for (Method m : type.getDeclaredMethods()) { if (m.getParameterTypes().length == 0 && isValidAnnotationMemberType(m.getReturnType())) { Object v1 = m.invoke(a1); Object v2 = m.invoke(a2); if (!memberEquals(m.getReturnType(), v1, v2)) { return false; } } } } catch (IllegalAccessException ex) { return false; } catch (InvocationTargetException ex) { return false; } return true; }
From source file:ml.shifu.shifu.container.meta.MetaFactory.java
/** * Iterate each property of Object, get the value and validate * // w w w .ja va2s .c o m * @param isGridSearch * - if grid search, ignore validation in train#params as they are set all as list * @param ptag * - the prefix of key to search @MetaItem * @param obj * - the object to validate * @return ValidateResult * If all items are OK, the ValidateResult.status will be true; * Or the ValidateResult.status will be false, ValidateResult.causes will contain the reasons * @throws Exception * any exception in validaiton */ public static ValidateResult iterateCheck(boolean isGridSearch, String ptag, Object obj) throws Exception { ValidateResult result = new ValidateResult(true); if (obj == null) { return result; } Class<?> cls = obj.getClass(); Field[] fields = cls.getDeclaredFields(); Class<?> parentCls = cls.getSuperclass(); if (!parentCls.equals(Object.class)) { Field[] pfs = parentCls.getDeclaredFields(); fields = (Field[]) ArrayUtils.addAll(fields, pfs); } for (Field field : fields) { if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !isJsonIngoreField(field)) { Method method = cls.getMethod("get" + getMethodName(field.getName())); Object value = method.invoke(obj); encapsulateResult(result, validate(isGridSearch, ptag + ITEM_KEY_SEPERATOR + field.getName(), value)); } } return result; }
From source file:io.github.benas.randombeans.util.ReflectionUtils.java
/** * Check if a field has a primitive type and matching default value which is set by the compiler. * * @param object instance to get the field value of * @param field field to check//from w ww .j a v a 2s . c o m * @throws IllegalAccessException if field cannot be accessed */ public static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field) throws IllegalAccessException { Class<?> fieldType = field.getType(); if (!fieldType.isPrimitive()) { return false; } Object fieldValue = getFieldValue(object, field); if (fieldValue == null) { return false; } if (fieldType.equals(boolean.class) && (boolean) fieldValue == false) { return true; } if (fieldType.equals(byte.class) && (byte) fieldValue == (byte) 0) { return true; } if (fieldType.equals(short.class) && (short) fieldValue == (short) 0) { return true; } if (fieldType.equals(int.class) && (int) fieldValue == 0) { return true; } if (fieldType.equals(long.class) && (long) fieldValue == 0L) { return true; } if (fieldType.equals(float.class) && (float) fieldValue == 0.0F) { return true; } if (fieldType.equals(double.class) && (double) fieldValue == 0.0D) { return true; } if (fieldType.equals(char.class) && (char) fieldValue == '\u0000') { return true; } return false; }
From source file:hu.javaforum.commons.ReflectionHelper.java
/** * Converts the string value to instance of the field class. * * @param fieldClass The field class//from www. j a v a2 s .c o m * @param stringValue The string value * @return The instance of the field class * @throws ParseException Throws when the string isn't parseable * @throws UnsupportedEncodingException If the Base64 stream contains non UTF-8 chars */ private static Object convertToOthers(final Class fieldClass, final String stringValue) throws ParseException, UnsupportedEncodingException { Object parameter = null; if (fieldClass.isEnum()) { parameter = Enum.valueOf((Class<Enum>) fieldClass, stringValue); } else if (fieldClass.equals(byte[].class)) { parameter = Base64.decodeBase64(stringValue.getBytes("UTF-8")); } else if (fieldClass.equals(Date.class)) { parameter = stringToDate(stringValue); } else if (fieldClass.equals(Calendar.class)) { Calendar cal = Calendar.getInstance(); cal.setTime(stringToDate(stringValue)); parameter = cal; } return parameter; }
From source file:com.xyz.util.ReflectionUtil.java
/** * ?clazzproperty.//from w w w. j av a2s . c o m * * @param value ? * @param clazz ???Class * @param propertyName ???Class. */ public static Object convertValue(Object value, Class<?> clazz, String propertyName) { try { Class<?> toType = BeanUtils.getPropertyDescriptor(clazz, propertyName).getPropertyType(); DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" }); ConvertUtils.register(dc, Date.class); //String???'' if (toType.equals(String.class)) value = "'" + value + "'"; return ConvertUtils.convert(value.toString(), toType); } catch (Exception e) { throw convertToUncheckedException(e); } }
From source file:net.jofm.metadata.PrimitiveFieldMetaData.java
private static Format createFormatter(Field fieldAnnotation, Class<?> fieldType, String fieldName, FormatConfig formatConfig) {/*from w w w . java 2s . co m*/ String defaultFormat = ""; Class<? extends Format> formatterClazz = null; if (Date.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) { defaultFormat = formatConfig.getDateFormat(); formatterClazz = DateFormat.class; } else if (String.class.isAssignableFrom(fieldType)) { formatterClazz = StringFormat.class; } else if (fieldType.equals(BigDecimal.class)) { defaultFormat = formatConfig.getBigDecimalFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) { defaultFormat = formatConfig.getShortFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) { defaultFormat = formatConfig.getIntFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) { defaultFormat = formatConfig.getLongFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) { defaultFormat = formatConfig.getFloatFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) { defaultFormat = formatConfig.getDoubleFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) { defaultFormat = formatConfig.getBooleanFormat(); formatterClazz = BooleanFormat.class; } else if (fieldType.isEnum()) { formatterClazz = EnumFormat.class; } if (fieldAnnotation.formatter() != null && !fieldAnnotation.formatter().equals(DefaultFormat.class)) { formatterClazz = fieldAnnotation.formatter(); } if (formatterClazz == null) { throw new FixedMappingException( "Unable to find formatter for field '" + fieldName + "' of type " + fieldType); } try { Constructor<?> c = formatterClazz .getConstructor(new Class[] { Pad.class, char.class, int.class, String.class }); Pad pad = fieldAnnotation.pad() == Pad.DEFAULT ? formatConfig.getPad() : fieldAnnotation.pad(); char padWith = fieldAnnotation.padWith() == Character.MIN_VALUE ? formatConfig.getPadWith() : fieldAnnotation.padWith(); int length = fieldAnnotation.length(); String format = StringUtils.isEmpty(fieldAnnotation.format()) ? defaultFormat : fieldAnnotation.format(); return (Format) c.newInstance(new Object[] { pad, padWith, length, format }); } catch (Exception e) { throw new FixedMappingException( "Unable to instantiate the formatter " + formatterClazz + " for field '" + fieldName + "'", e); } }
From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java
/** * Creates a column family suitable for use with the entity. We try to * extract the name of the CQL3 table from a {@link javax.persistence.Table} * annotation. If the annotation is absent or the "name" parameter is null, * we will use the "name" parameter of the {@link javax.persistence.Entity} * annotation. If that name is null, we will use the name of the class. * * @param entityClazz//from ww w. j ava 2 s.com * @return a column family object suitable for use with the given entity. */ public static <T> ColumnFamily<String, String> inferColumnFamily(Class<T> entityClazz) { Preconditions.checkNotNull(entityClazz); String tableName = null; for (Annotation annotation : entityClazz.getDeclaredAnnotations()) { Class<? extends Annotation> annotationType = annotation.annotationType(); /* * @Table has the highest priority. Then follows @Entity. Lastly, * the name of the entity's class. */ if (annotationType.equals(javax.persistence.Table.class)) { javax.persistence.Table table = ((javax.persistence.Table) annotation); if (table.name() != null) { tableName = table.name(); } } else if (annotationType.equals(javax.persistence.Entity.class)) { javax.persistence.Entity entity = ((javax.persistence.Entity) annotation); if (tableName == null && entity.name() != null) { tableName = entity.name(); } } } if (tableName == null) { tableName = entityClazz.getSimpleName(); } tableName = normalizeCqlElementName(tableName); ColumnFamily<String, String> columnFamily = ColumnFamily.newColumnFamily(tableName, StringSerializer.get(), StringSerializer.get()); return columnFamily; }
From source file:com.github.strawberry.guice.config.ConfigLoader.java
private static Option getFromProperties(Map properties, final Field field, final Config annotation) { Object value = null;//from w w w. j a v a2s. co m Class<?> fieldType = field.getType(); String pattern = annotation.value(); boolean allowNull = annotation.allowNull(); Set<String> matchingKeys = getKeys(properties, pattern); if (matchingKeys.size() == 1) { String matchingKey = Iterables.getOnlyElement(matchingKeys); if (fieldType.equals(char[].class)) { value = properties.get(matchingKey).toString().toCharArray(); } else if (fieldType.equals(Character[].class)) { value = ArrayUtils.toObject(properties.get(matchingKey).toString().toCharArray()); } else if (fieldType.equals(char.class) || fieldType.equals(Character.class)) { String toConvert = properties.get(matchingKey).toString(); if (toConvert.length() == 1) { value = properties.get(matchingKey).toString().charAt(0); } else { throw ConversionException.of(toConvert, matchingKey, fieldType); } } else if (fieldType.equals(String.class)) { value = properties.get(matchingKey); } else if (fieldType.equals(byte[].class)) { if (properties.containsKey(matchingKey)) { value = properties.get(matchingKey).toString().getBytes(); } else { value = null; } } else if (fieldType.equals(Byte[].class)) { value = ArrayUtils.toObject(properties.get(matchingKey).toString().getBytes()); } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) { String toConvert = properties.get(matchingKey).toString(); if (BOOLEAN.matcher(toConvert).matches()) { value = TRUE.matcher(toConvert).matches(); } else { throw ConversionException.of(toConvert, matchingKey, fieldType); } } else if (Map.class.isAssignableFrom(fieldType)) { value = mapOf(field, properties, matchingKey); } else if (Collection.class.isAssignableFrom(fieldType)) { value = collectionOf(field, properties, matchingKey); } else { String toConvert = properties.get(matchingKey).toString(); try { if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) { value = Byte.parseByte(properties.get(matchingKey).toString()); } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) { value = Short.parseShort(toConvert); } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) { value = Integer.parseInt(toConvert); } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) { value = Long.parseLong(toConvert); } else if (fieldType.equals(BigInteger.class)) { value = new BigInteger(toConvert); } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) { value = Float.parseFloat(toConvert); } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) { value = Double.parseDouble(toConvert); } else if (fieldType.equals(BigDecimal.class)) { value = new BigDecimal(toConvert); } } catch (NumberFormatException exception) { throw ConversionException.of(exception, toConvert, matchingKey, fieldType); } } } else if (matchingKeys.size() > 1) { if (Map.class.isAssignableFrom(fieldType)) { value = nestedMapOf(field, properties, matchingKeys); } else if (Collection.class.isAssignableFrom(fieldType)) { value = nestedCollectionOf(field, properties, matchingKeys); } } else { if (!allowNull) { value = nonNullValueOf(fieldType); } } return Option.fromNull(value); }
From source file:com.liusoft.dlog4j.search.SearchProxy.java
/** * ?/* w ww . j a v a 2 s . c o m*/ * @param params * @return * @throws Exception */ public static List search(SearchParameter params) throws Exception { if (params == null) return null; SearchEnabled searching = (SearchEnabled) params.getSearchObject().newInstance(); StringBuffer path = new StringBuffer(_baseIndexPath); path.append(searching.name()); File f = new File(path.toString()); if (!f.exists()) return null; IndexSearcher searcher = new IndexSearcher(path.toString()); //? BooleanQuery comboQuery = new BooleanQuery(); int _query_count = 0; StringTokenizer st = new StringTokenizer(params.getSearchKey()); while (st.hasMoreElements()) { String q = st.nextToken(); String[] indexFields = searching.getIndexFields(); for (int i = 0; i < indexFields.length; i++) { QueryParser qp = new QueryParser(indexFields[i], analyzer); try { Query subjectQuery = qp.parse(q); comboQuery.add(subjectQuery, BooleanClause.Occur.SHOULD); _query_count++; } catch (Exception e) { log.error("Add query parameter failed. key=" + q, e); } } } if (_query_count == 0)//? return null; //?? MultiFilter multiFilter = null; HashMap conds = params.getConditions(); if (conds != null) { Iterator keys = conds.keySet().iterator(); while (keys.hasNext()) { if (multiFilter == null) multiFilter = new MultiFilter(0); String key = (String) keys.next(); multiFilter.add(new FieldFilter(key, conds.get(key).toString())); } } /* * Creates a sort, possibly in reverse, * by terms in the given field with the type of term values explicitly given. */ SortField[] s_fields = new SortField[2]; s_fields[0] = SortField.FIELD_SCORE; s_fields[1] = new SortField(searching.getKeywordField(), SortField.INT, true); Sort sort = new Sort(s_fields); Hits hits = searcher.search(comboQuery, multiFilter, sort); int numResults = hits.length(); //System.out.println(numResults + " found............................"); int result_count = Math.min(numResults, MAX_RESULT_COUNT); List results = new ArrayList(result_count); for (int i = 0; i < result_count; i++) { Document doc = (Document) hits.doc(i); //Java Object result = params.getSearchObject().newInstance(); Enumeration fields = doc.fields(); while (fields.hasMoreElements()) { Field field = (Field) fields.nextElement(); //System.out.println(field.name()+" -- "+field.stringValue()); if (CLASSNAME_FIELD.equals(field.name())) continue; //? if (!field.isStored()) continue; //System.out.println("=========== begin to mapping ============"); //String --> anything Class fieldType = getNestedPropertyType(result, field.name()); //System.out.println(field.name()+", class = " + fieldType.getName()); Object fieldValue = null; if (fieldType.equals(Date.class)) fieldValue = new Date(Long.parseLong(field.stringValue())); else fieldValue = ConvertUtils.convert(field.stringValue(), fieldType); //System.out.println(fieldValue+", class = " + fieldValue.getClass().getName()); setNestedProperty(result, field.name(), fieldValue); } results.add(result); } return results; }