List of usage examples for java.lang Class getDeclaredFields
@CallerSensitive public Field[] getDeclaredFields() throws SecurityException
From source file:com.beetle.framework.util.ObjectUtil.java
private static Field[] getObjAllFields(Object object) { Class<?> clazz = object.getClass(); List<Field> fieldList = new ArrayList<>(); while (clazz != null) { fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass();/*w w w. jav a2s .c o m*/ } Field[] fields = new Field[fieldList.size()]; fieldList.toArray(fields); return fields; }
From source file:com.greenline.hrs.admin.util.db.SchemaExport.java
public static String exportMySQL(Class type) { if (type == null) { return StringUtils.EMPTY; }//ww w . j a v a2 s . com String tableName = type.getName().substring(type.getName().lastIndexOf('.') + 1); tableName = StringUtil.underscoreName(tableName); StringBuilder sb = new StringBuilder(); sb.append("DROP TABLE IF EXISTS `" + tableName + "`;" + LINUX_LINE_DELIMITER); sb.append("CREATE TABLE `"); sb.append(tableName); sb.append("` (" + LINUX_LINE_DELIMITER + LINUX_LINE_DELIMITER); sb.append("`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '',"); Field[] fields = type.getDeclaredFields(); for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers())) { sb.append("`" + StringUtil.underscoreName(field.getName()) + "` " + JdbcColumnUtil.getColumeTypeDesc(field.getType()) + " NOT NULL COMMENT ''," + LINUX_LINE_DELIMITER); } } sb.append("PRIMARY KEY (`id`)" + LINUX_LINE_DELIMITER); sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); return sb.toString(); }
From source file:Main.java
public static String createTableSql(Class<?> classs, String tableName, String... extraColumns) { mBuffer.setLength(0);/* www .j a va 2 s .co m*/ mBuffer.append("CREATE TABLE IF NOT EXISTS "); if (!TextUtils.isEmpty(tableName)) { mBuffer.append(tableName); } else { String className = classs.getSimpleName(); if (className.contains("[]")) { throw new IllegalArgumentException("Can not create array class table"); } mBuffer.append(classs.getSimpleName()); } mBuffer.append("(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "); Field[] fields = classs.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (field.getType() == Integer.class) { mBuffer.append(field.getName() + " INTEGER,"); } else if (field.getType() == Double.class || field.getType() == Float.class) { mBuffer.append(field.getName() + " REAL,"); } else if (field.getType() == String.class) { mBuffer.append(field.getName() + " TEXT,"); } else if (field.getType() == Boolean.class) { mBuffer.append(field.getName() + " INTEGER,"); } else if (field.getType() == List.class || field.getType() == ArrayList.class) { mBuffer.append(field.getName() + " TEXT,"); } } if (extraColumns != null && extraColumns.length != 0) { for (int i = 0; i < extraColumns.length; i++) { mBuffer.append(extraColumns[i]); if (i != extraColumns.length - 1) { mBuffer.append(","); } else { mBuffer.append(")"); } } } return mBuffer.toString(); }
From source file:de.micromata.genome.util.runtime.ClassUtils.java
/** * Set all String field to empty on current class. * * @param object the object//from w ww . j a va 2 s.co m * @param exceptClass the except class * @throws IllegalArgumentException the illegal argument exception * @throws IllegalAccessException the illegal access exception */ // CHECKSTYLE.OFF com.puppycrawl.tools.checkstyle.checks.metrics.CyclomaticComplexityCheck Trivial code. public static void fillDefaultEmptyFieldsIfEmpty(Object object, Class<?>... exceptClass) // NOSONAR "Methods should not be too complex" trivial throws IllegalArgumentException, IllegalAccessException { Class<?> currentClazz = object.getClass(); List exClazzes = Arrays.asList(exceptClass); while (currentClazz.getSuperclass() != null) { if (exClazzes.contains(currentClazz) == false) { Field[] fields = currentClazz.getDeclaredFields(); for (Field field : fields) { if (String.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, ""); } } if (Integer.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, 0); } } if (BigDecimal.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, BigDecimal.ZERO); } } if (Date.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, new Date()); } } } } currentClazz = currentClazz.getSuperclass(); } }
From source file:com.bosscs.spark.commons.utils.Utils.java
/** * Returns an instance clone.//from w ww.j av a 2 s . c o m * this method gets every class property by reflection, including its parents properties * @param t * @param <T> * @return T object. */ public static <T> T cloneObjectWithParents(T t) throws IllegalAccessException, InstantiationException { T clone = (T) t.getClass().newInstance(); List<Field> allFields = new ArrayList<>(); Class parentClass = t.getClass().getSuperclass(); while (parentClass != null) { Collections.addAll(allFields, parentClass.getDeclaredFields()); parentClass = parentClass.getSuperclass(); } Collections.addAll(allFields, t.getClass().getDeclaredFields()); for (Field field : allFields) { int modifiers = field.getModifiers(); //We skip final and static fields if ((Modifier.FINAL & modifiers) != 0 || (Modifier.STATIC & modifiers) != 0) { continue; } field.setAccessible(true); Object value = field.get(t); if (Collection.class.isAssignableFrom(field.getType())) { Collection collection = (Collection) field.get(clone); if (collection == null) { collection = (Collection) field.get(t).getClass().newInstance(); } collection.addAll((Collection) field.get(t)); value = collection; } else if (Map.class.isAssignableFrom(field.getType())) { Map clonMap = (Map) field.get(t).getClass().newInstance(); clonMap.putAll((Map) field.get(t)); value = clonMap; } field.set(clone, value); } return clone; }
From source file:com.unboundid.scim2.common.utils.SchemaUtils.java
/** * This method will find a java Field for with a particular name. If * needed, this method will search through super classes. The field * does not need to be public./*from w ww. ja v a 2s . c o m*/ * * @param cls the java Class to search. * @param fieldName the name of the field to find. * @return the java field. */ public static Field findField(final Class<?> cls, final String fieldName) { Class<?> currentClass = cls; while (currentClass != null) { Field[] fields = currentClass.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals(fieldName)) { return field; } } currentClass = currentClass.getSuperclass(); } return null; }
From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java
public static String findEnumFieldValueUncached(Class classType, String toStringValue) { for (Field field : classType.getDeclaredFields()) { XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class); if (xmlEnumValue != null && field.getName().equals(toStringValue)) { return xmlEnumValue.value(); }/*from w w w . j av a 2s. c o m*/ } return null; }
From source file:edu.usu.sdl.openstorefront.util.ReflectionUtil.java
/** * This gets all declared field of the whole object hierarchy * * @param typeClass/*www. j ava 2s . com*/ * @return */ public static List<Field> getAllFields(Class typeClass) { Objects.requireNonNull(typeClass, "Class is required"); List<Field> fields = new ArrayList<>(); if (typeClass.getSuperclass() != null) { fields.addAll(getAllFields(typeClass.getSuperclass())); } for (Field field : typeClass.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers()) == false && Modifier.isFinal(field.getModifiers()) == false) { fields.add(field); } } return fields; }
From source file:net.minecraftforge.common.util.EnumHelper.java
@SuppressWarnings({ "unchecked", "serial" }) @Nullable//from w w w . j a va2s .c om private static <T extends Enum<?>> T addEnum(boolean test, final Class<T> enumType, @Nullable String enumName, final Class<?>[] paramTypes, @Nullable Object[] paramValues) { if (!isSetup) { setup(); } Field valuesField = null; Field[] fields = enumType.getDeclaredFields(); for (Field field : fields) { String name = field.getName(); if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards { valuesField = field; break; } } int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC | Modifier.FINAL | 0x1000 /*SYNTHETIC*/; if (valuesField == null) { String valueType = String.format("[L%s;", enumType.getName().replace('.', '/')); for (Field field : fields) { if ((field.getModifiers() & flags) == flags && field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't.. { valuesField = field; break; } } } if (valuesField == null) { final List<String> lines = Lists.newArrayList(); lines.add(String.format("Could not find $VALUES field for enum: %s", enumType.getName())); lines.add(String.format("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF)); lines.add(String.format("Flags: %s", String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0'))); lines.add("Fields:"); for (Field field : fields) { String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0'); lines.add(String.format(" %s %s: %s", mods, field.getName(), field.getType().getName())); } for (String line : lines) FMLLog.log.fatal(line); if (test) { throw new EnhancedRuntimeException("Could not find $VALUES field for enum: " + enumType.getName()) { @Override protected void printStackTrace(WrappedPrintStream stream) { for (String line : lines) stream.println(line); } }; } return null; } if (test) { Object ctr = null; Exception ex = null; try { ctr = getConstructorAccessor(enumType, paramTypes); } catch (Exception e) { ex = e; } if (ctr == null || ex != null) { throw new EnhancedRuntimeException( String.format("Could not find constructor for Enum %s", enumType.getName()), ex) { private String toString(Class<?>[] cls) { StringBuilder b = new StringBuilder(); for (int x = 0; x < cls.length; x++) { b.append(cls[x].getName()); if (x != cls.length - 1) b.append(", "); } return b.toString(); } @Override protected void printStackTrace(WrappedPrintStream stream) { stream.println("Target Arguments:"); stream.println(" java.lang.String, int, " + toString(paramTypes)); stream.println("Found Constructors:"); for (Constructor<?> ctr : enumType.getDeclaredConstructors()) { stream.println(" " + toString(ctr.getParameterTypes())); } } }; } return null; } valuesField.setAccessible(true); try { T[] previousValues = (T[]) valuesField.get(enumType); T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues); setFailsafeFieldValue(valuesField, null, ArrayUtils.add(previousValues, newValue)); cleanEnumCache(enumType); return newValue; } catch (Exception e) { FMLLog.log.error("Error adding enum with EnumHelper.", e); throw new RuntimeException(e); } }
From source file:cn.org.awcp.core.mybatis.mapper.EntityHelper.java
/** * ?Field//from w w w.j a va 2s . co m * * @param entityClass * @param fieldList * @return */ private static List<Field> getAllField(Class<?> entityClass, List<Field> fieldList) { if (fieldList == null) { fieldList = new ArrayList<Field>(); } if (entityClass.equals(Object.class)) { return fieldList; } Field[] fields = entityClass.getDeclaredFields(); for (Field field : fields) { // ??bug#2 if (!Modifier.isStatic(field.getModifiers())) { fieldList.add(field); } } if (entityClass.getSuperclass() != null && !entityClass.getSuperclass().equals(Object.class) && !Map.class.isAssignableFrom(entityClass.getSuperclass()) && !Collection.class.isAssignableFrom(entityClass.getSuperclass())) { return getAllField(entityClass.getSuperclass(), fieldList); } return fieldList; }