// obj: "object with properties" to write private void writeObject(Object obj) throws NoSuchMethodException, InstantiationException, InvocationTargetException, IllegalAccessException, SecurityException { // begin bean encoding: this.driver.startElement(DTD.ELEMENT_OBJECT); Class cls = obj.getClass(); final String mappedName = this.context.aliasFor(cls); this.driver.setAttribute( DTD.ATTRIBUTE_CLASS, (mappedName != null ? mappedName : cls.getName())); // encode properties: while (cls != Object.class) { // process inheritance: for (Field f : cls.getDeclaredFields()) { // process composition: if (Modifier.isStatic(f.getModifiers()) || !ReflectionUtil.hasClassFieldProperty(cls, f) || this.context.excluded(f)) { continue; // skip static or non-property or excluded field. } // get property field: if (!f.isAccessible()) { f.setAccessible(true); } // write property value: final String aliasedFieldName = this.context.aliasFor(f, f.getName()); this.driver.startElement(aliasedFieldName); this.write0(f.get(obj)); this.driver.endElement(); } cls = cls.getSuperclass(); } // end bean encoding: this.driver.endElement(); }
private int getNumNonSerialVersionUIDFields(Class clazz) { Field[] declaredFields = clazz.getDeclaredFields(); int numFields = declaredFields.length; List<Field> fieldList = Arrays.asList(declaredFields); // System.out.println(clazz); // // for (Field field : fieldList) { // System.out.println(field.getNode()); // } for (Field field : fieldList) { if (field.getName().equals("serialVersionUID")) { numFields--; } if (field.getName().equals("this$0")) { numFields--; } } // System.out.println(numFields); return numFields; }
/** * @param clazz the class to be handled (read from and wrote to) * @param file the file to be processed */ public void handleConfig(Class<?> clazz, File file) { if (!hasRun) { hasRun = true; for (Field field : clazz.getDeclaredFields()) { for (Annotation annotation : field.getAnnotations()) { if (annotation.annotationType() == Config.String.class) handleString(clazz, field, (Config.String) annotation); else if (annotation.annotationType() == Config.Integer.class) handleInteger(clazz, field, (Config.Integer) annotation); else if (annotation.annotationType() == Config.Boolean.class) handleBoolean(clazz, field, (Config.Boolean) annotation); else if (annotation.annotationType() == Config.List.class) handleList(clazz, field, (Config.List) annotation); else if (annotation.annotationType() == Config.Map.class) handleMap(clazz, field, (Config.Map) annotation); else if (annotation.annotationType() == Config.Long.class) handleLong(clazz, field, (Config.Long) annotation); else if (annotation.annotationType() == Config.Float.class) handleFloat(clazz, field, (Config.Float) annotation); else if (annotation.annotationType() == Config.Double.class) handleDouble(clazz, field, (Config.Double) annotation); else if (annotation.annotationType() == Config.Character.class) handleCharacter(clazz, field, (Config.Character) annotation); } } } try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String line; while ((line = reader.readLine()) != null) { if (line.contains("{")) { char[] chars = line.toCharArray(); boolean hasNotEncounteredText = true; StringBuilder stringBuilder = new StringBuilder(); for (Character character : chars) { if ((!character.equals(' ') && !character.equals('\t')) || hasNotEncounteredText) { hasNotEncounteredText = false; stringBuilder.append(character); } else if (character.equals(' ')) break; } categories .getOrDefault(stringBuilder.toString(), categories.get("General")) .read(clazz, reader); } } } catch (IOException ignored) { } StringBuilder stringBuilder = new StringBuilder(); categories.values().forEach(category -> category.write(stringBuilder)); String fileString = stringBuilder.toString(); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) { writer.append(fileString); } catch (IOException ignored) { } }
/** * 通过反射的方式遍历对象的属性和属性值,方便调试 * * @param o 要遍历的对象 * @throws Exception */ public static void reflect(Object o) throws Exception { Class cls = o.getClass(); Field[] fields = cls.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field f = fields[i]; f.setAccessible(true); Util.log(f.getName() + " -> " + f.get(o)); } }
private static List<Field> buildFields(Class infoClass) { List<Field> fields = new ArrayList<>(); for (Field field : infoClass.getDeclaredFields()) { if (!Modifier.isStatic(field.getModifiers())) { fields.add(field); } } return fields; }
private static Field[] getAllFields(Class cls) { ArrayList<Field> res = new ArrayList<>(); Class c = cls; while (c != View.class) { assert Utils.check(c != null); res.addAll(Arrays.asList(c.getDeclaredFields())); c = c.getSuperclass(); } return res.toArray(new Field[res.size()]); }
private Field findSqlMapExecutorDelegate(SqlMapClient sqlMapClient) { Class<?> searchType = sqlMapClient.getClass(); while (!Object.class.equals(searchType) && searchType != null) { Field[] fields = searchType.getDeclaredFields(); for (Field field : fields) { if (SqlMapExecutorDelegate.class.isAssignableFrom(field.getType())) return field; } searchType = searchType.getSuperclass(); } return null; }
private void InitFieldCmd(ICmd cmd, Hashtable<FieldCmdKind, Object> fieldsValue) { Class c = cmd.getClass(); // Класс рассматриваемой команды. Field f[]; // Набор полей рассматриваемого класса. while (c != null) { f = c.getDeclaredFields(); for (Field iF : f) { setFieldValue(iF, cmd, fieldsValue); } c = c.getSuperclass(); } }
private static void convertProtocolToAsciidocTable(Properties props, Class<Protocol> clazz) throws Exception { boolean isUnsupported = clazz.isAnnotationPresent(Unsupported.class); if (isUnsupported) return; Map<String, String> nameToDescription = new TreeMap<>(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Property.class)) { String property = field.getName(); Property annotation = field.getAnnotation(Property.class); String desc = annotation.description(); nameToDescription.put(property, desc); } } // iterate methods Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Property.class)) { Property annotation = method.getAnnotation(Property.class); String desc = annotation.description(); if (desc == null || desc.isEmpty()) desc = "n/a"; String name = annotation.name(); if (name.length() < 1) { name = Util.methodNameToAttributeName(method.getName()); } nameToDescription.put(name, desc); } } // do we have more than one property (superclass Protocol has only one property (stats)) if (nameToDescription.isEmpty()) return; List<String[]> rows = new ArrayList<>(nameToDescription.size() + 1); rows.add(new String[] {"Name", "Description"}); for (Map.Entry<String, String> entry : nameToDescription.entrySet()) rows.add(new String[] {entry.getKey(), entry.getValue()}); String tmp = createAsciidocTable( rows, clazz.getSimpleName(), "[align=\"left\",width=\"90%\",cols=\"2,10\",options=\"header\"]"); props.put(clazz.getSimpleName(), tmp); }
/** Reflect operations demo */ public static void reflect(Object obj) { // `cls用于描述对象所属的类` Class cls = obj.getClass(); print("Class Name: " + cls.getCanonicalName()); // `fields包含对象的所有属性` Field[] fields = cls.getDeclaredFields(); print("List of fields:"); for (Field f : fields) { print(String.format("%30s %15s", f.getType(), f.getName())); } // `methods包含对象的所有方法` Method[] methods = cls.getDeclaredMethods(); print("List of methods:"); for (Method m : methods) print( String.format( "%30s %15s %30s", m.getReturnType(), m.getName(), Arrays.toString(m.getParameterTypes()))); Constructor[] constructors = cls.getConstructors(); print("List of contructors:"); for (Constructor c : constructors) print(String.format("%30s %15s", c.getName(), Arrays.toString(c.getParameterTypes()))); }
/** * Checks all of the classes in the serialization scope that implement TetradSerializable to make * sure all of their fields are either themselves (a) primitive, (b) TetradSerializable, or (c) * assignable from types designated as safely serializable by virtue of being included in the * safelySerializableTypes array (see), or are arrays whose lowest order component types satisfy * either (a), (b), or (c). Safely serializable classes in the Java API currently include * collections classes, plus String and Class. Collections classes are included, since their types * will be syntactically checkable in JDK 1.5. String and Class are members of a broader type of * Class whose safely can by checked by making sure there is no way to pass into them via * constructor or method argument any object that is not TetradSerializable or safely * serializable. But it's easy enough now to just make a list. * * @see #safelySerializableTypes */ public void checkNestingOfFields() { List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class); boolean foundUnsafeField = false; for (Object aClass : classes) { Class clazz = (Class) aClass; if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) { continue; } Field[] fields = clazz.getDeclaredFields(); FIELDS: for (Field field : fields) { // System.out.println(field); if (Modifier.isTransient(field.getModifiers())) { continue; } if (Modifier.isStatic(field.getModifiers())) { continue; } Class type = field.getType(); while (type.isArray()) { type = type.getComponentType(); } if (type.isPrimitive()) { continue; } if (type.isEnum()) { continue; } // // Printing out Collections fields temporarily. // if (Collection.class.isAssignableFrom(type)) { // System.out.println("COLLECTION FIELD: " + field); // } // // if (Map.class.isAssignableFrom(type)) { // System.out.println("MAP FIELD: " + field); // } if (TetradSerializable.class.isAssignableFrom(type) && !TetradSerializableExcluded.class.isAssignableFrom(clazz)) { continue; } for (Class safelySerializableClass : safelySerializableTypes) { if (safelySerializableClass.isAssignableFrom(type)) { continue FIELDS; } } // A reference in an inner class to the outer class. if (field.getName().equals("this$0")) { continue; } System.out.println("UNSAFE FIELD:" + field); foundUnsafeField = true; } } if (foundUnsafeField) { throw new RuntimeException("Unsafe serializable fields found. Please " + "fix immediately."); } }
public boolean prepareDelegate( Object subject, CommandSession session, List<Object> params, CommandArguments args) throws Exception { args.subject = subject; // Introspect for (Class type = subject.getClass(); type != null; type = type.getSuperclass()) { for (Field field : type.getDeclaredFields()) { Option option = field.getAnnotation(Option.class); if (option != null) { args.options.put(option, field); } Argument argument = field.getAnnotation(Argument.class); if (argument != null) { if (Argument.DEFAULT.equals(argument.name())) { final Argument delegate = argument; final String name = field.getName(); argument = new Argument() { public String name() { return name; } public String description() { return delegate.description(); } public boolean required() { return delegate.required(); } public int index() { return delegate.index(); } public boolean multiValued() { return delegate.multiValued(); } public String valueToShowInHelp() { return delegate.valueToShowInHelp(); } public Class<? extends Annotation> annotationType() { return delegate.annotationType(); } }; } args.arguments.put(argument, field); int index = argument.index(); while (args.orderedArguments.size() <= index) { args.orderedArguments.add(null); } if (args.orderedArguments.get(index) != null) { throw new IllegalArgumentException("Duplicate argument index: " + index); } args.orderedArguments.set(index, argument); } } } // Check indexes are correct for (int i = 0; i < args.orderedArguments.size(); i++) { if (args.orderedArguments.get(i) == null) { throw new IllegalArgumentException("Missing argument for index: " + i); } } // Populate Map<Option, Object> optionValues = new TreeMap<Option, Object>(CommandArguments.OPTION_COMPARATOR); Map<Argument, Object> argumentValues = new HashMap<Argument, Object>(); boolean processOptions = true; int argIndex = 0; for (Iterator<Object> it = params.iterator(); it.hasNext(); ) { Object param = it.next(); // Check for help if (HELP.name().equals(param) || Arrays.asList(HELP.aliases()).contains(param)) { printUsageDelegate(session, subject, args.options, args.arguments, System.out); return false; } if (processOptions && param instanceof String && ((String) param).startsWith("-")) { boolean isKeyValuePair = ((String) param).indexOf('=') != -1; String name; Object value = null; if (isKeyValuePair) { name = ((String) param).substring(0, ((String) param).indexOf('=')); value = ((String) param).substring(((String) param).indexOf('=') + 1); } else { name = (String) param; } Option option = null; for (Option opt : args.options.keySet()) { if (name.equals(opt.name()) || Arrays.asList(opt.aliases()).contains(name)) { option = opt; break; } } if (option == null) { throw new CommandException( Ansi.ansi() .fg(Ansi.Color.RED) .a("Error executing command ") .a(scope) .a(":") .a(Ansi.Attribute.INTENSITY_BOLD) .a(name) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(" undefined option ") .a(Ansi.Attribute.INTENSITY_BOLD) .a(param) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .fg(Ansi.Color.DEFAULT) .toString(), "Undefined option: " + param); } Field field = args.options.get(option); if (value == null && (field.getType() == boolean.class || field.getType() == Boolean.class)) { value = Boolean.TRUE; } if (value == null && it.hasNext()) { value = it.next(); } if (value == null) { throw new CommandException( Ansi.ansi() .fg(Ansi.Color.RED) .a("Error executing command ") .a(scope) .a(":") .a(Ansi.Attribute.INTENSITY_BOLD) .a(name) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(" missing value for option ") .a(Ansi.Attribute.INTENSITY_BOLD) .a(param) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .fg(Ansi.Color.DEFAULT) .toString(), "Missing value for option: " + param); } if (option.multiValued()) { List<Object> l = (List<Object>) optionValues.get(option); if (l == null) { l = new ArrayList<Object>(); optionValues.put(option, l); } l.add(value); } else { optionValues.put(option, value); } } else { processOptions = false; if (argIndex >= args.orderedArguments.size()) { throw new CommandException( Ansi.ansi() .fg(Ansi.Color.RED) .a("Error executing command ") .a(scope) .a(":") .a(Ansi.Attribute.INTENSITY_BOLD) .a(name) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(": too many arguments specified") .fg(Ansi.Color.DEFAULT) .toString(), "Too many arguments specified"); } Argument argument = args.orderedArguments.get(argIndex); if (!argument.multiValued()) { argIndex++; } if (argument.multiValued()) { List<Object> l = (List<Object>) argumentValues.get(argument); if (l == null) { l = new ArrayList<Object>(); argumentValues.put(argument, l); } l.add(param); } else { argumentValues.put(argument, param); } } } // Check required arguments / options for (Option option : args.options.keySet()) { if (option.required() && optionValues.get(option) == null) { throw new CommandException( Ansi.ansi() .fg(Ansi.Color.RED) .a("Error executing command ") .a(scope) .a(":") .a(Ansi.Attribute.INTENSITY_BOLD) .a(name) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(": option ") .a(Ansi.Attribute.INTENSITY_BOLD) .a(option.name()) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(" is required") .fg(Ansi.Color.DEFAULT) .toString(), "Option " + option.name() + " is required"); } } for (Argument argument : args.arguments.keySet()) { if (argument.required() && argumentValues.get(argument) == null) { throw new CommandException( Ansi.ansi() .fg(Ansi.Color.RED) .a("Error executing command ") .a(scope) .a(":") .a(Ansi.Attribute.INTENSITY_BOLD) .a(name) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(": argument ") .a(Ansi.Attribute.INTENSITY_BOLD) .a(argument.name()) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(" is required") .fg(Ansi.Color.DEFAULT) .toString(), "Argument " + argument.name() + " is required"); } } // Convert and inject values for (Map.Entry<Option, Object> entry : optionValues.entrySet()) { Field field = args.options.get(entry.getKey()); Object value; try { value = convert(subject, entry.getValue(), field.getGenericType()); } catch (Exception e) { throw new CommandException( Ansi.ansi() .fg(Ansi.Color.RED) .a("Error executing command ") .a(scope) .a(":") .a(Ansi.Attribute.INTENSITY_BOLD) .a(name) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(": unable to convert option ") .a(Ansi.Attribute.INTENSITY_BOLD) .a(entry.getKey().name()) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(" with value '") .a(entry.getValue()) .a("' to type ") .a(new GenericType(field.getGenericType()).toString()) .fg(Ansi.Color.DEFAULT) .toString(), "Unable to convert option " + entry.getKey().name() + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), e); } field.setAccessible(true); field.set(subject, value); } for (Map.Entry<Argument, Object> entry : argumentValues.entrySet()) { Field field = args.arguments.get(entry.getKey()); Object value; try { value = convert(subject, entry.getValue(), field.getGenericType()); } catch (Exception e) { throw new CommandException( Ansi.ansi() .fg(Ansi.Color.RED) .a("Error executing command ") .a(scope) .a(":") .a(Ansi.Attribute.INTENSITY_BOLD) .a(name) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(": unable to convert argument ") .a(Ansi.Attribute.INTENSITY_BOLD) .a(entry.getKey().name()) .a(Ansi.Attribute.INTENSITY_BOLD_OFF) .a(" with value '") .a(entry.getValue()) .a("' to type ") .a(new GenericType(field.getGenericType()).toString()) .fg(Ansi.Color.DEFAULT) .toString(), "Unable to convert argument " + entry.getKey().name() + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), e); } field.setAccessible(true); field.set(subject, value); } return true; }