Source: github.com/ddb12138/ju…

involvingisAssignableForm, annotation, reflection complete the default Settings

IsAssignableForm method differs from the instanceof keyword

Inherit the Angle Determine type
isAssignableForm Class inheritance perspective Determines whether it is the parent of a class
instanceof Instance inheritance perspective Determines whether a class is a subclass

Explanation:

Parent class.isAssignableFrom(subclass.class)

Subclass instanceof parent type ==> is used to determine whether the instance is an instanceof the parent class

Code:

public class Main1 {
    public static void main(String[] args) {
        
        / / 1. Is the parent class
        boolean isFlag = Number.class.isAssignableFrom(Double.class);
        System.out.println(isFlag);
        / / output: true
        
	/ / (2) is itself
        boolean isFlag1 =Double.class.isAssignableFrom(Number.class);
        System.out.println(isFlag1);
        / / output: true
		
        / / 3. The subclass
        boolean isFlag2 =Double.class.isAssignableFrom(Double.class);
        System.out.println(isFlag2);
        / / output: false

        // Subclass instance instanceof parent class type
        Object object1 = new ArrayList<>();
        if (object1 instanceof ArrayList) {
            System.out.println("I'm an instance of ArrayList.");
            // Output: I am an instance of ArrayList}}}Copy the code

Annotation class + reflection +isAssignableForm completes the injection

Usage scenarios: Setting default values for object fields, don’t want to modify the constructor, don’t want to use the set method?

It involves custom annotation classes, entity classes, and processor classes, with emphasis on processor classes

  • Advantages:

    • No constructors are involved
    • The set method is not used
    • handsome
  • Disadvantages:

    • The original type is not available

    • Performance degradation

    • Security issues

  1. Package structure

  1. Custom annotation classes

    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface ParamAnno {
        String value(a);
    }
    Copy the code
  2. Entity class

    public class Person {
        @ParamAnno(value = "ddb12138")
        private String name;
        @ParamAnno(value = "13")
        private Integer age;
        @ ParamAnno (value = "d" 20.2)
        private Double money;
        @ParamAnno(value = "true")
        private Boolean man;
        @paramanno (value = ParamAnno)
        private Character lastName='no';
        public Person(a) {}/ / get&set method
        / / the toString method.Copy the code

    4. Processor classes

    public class ParamProcessor {
        public static void setDefalutValue(Object obj) {
            // Get the Class passed in first
            Class source = obj.getClass();
            ArrayList<Field> fields = new ArrayList<>();
            while(source ! =null) {
                // Get all attributes (including private attributes)
                fields.addAll(Arrays.asList(source.getDeclaredFields()));
                source = source.getSuperclass();
            }
            for (Field field : fields) {
                // Set the release permission
                field.setAccessible(true);
                // Determine if the attribute is annotated
                if (field.isAnnotationPresent(ParamAnno.class)) {
                    try {
                        // Returns the value of the Field represented by this Field on the specified object
                        Object val = field.get(obj);
                        // You can use the judgment statement to select whether the injected object has a null value (that is, whether the annotated value should be overridden if there was one), and note that the value of lastName is printed at the end
                        if(val ! =null) {
                            continue;
                        }
                        // Get the type of the attribute
                        Class type = field.getType();
                        if (type.isPrimitive()) {
                            / / determine whether for the original class (Boolean, char, byte, short, int, long, float, double)
                            continue;
                        }
                        // Get the value on the annotation
                        String defVal = field.getAnnotation(ParamAnno.class).value();
                        if (String.class.isAssignableFrom(type)) {
                            field.set(obj, defVal);
                        } else if (Number.class.isAssignableFrom(type)) {
                            if (Byte.class.isAssignableFrom(type)) {
                                field.set(obj, Byte.valueOf(defVal));
                            } else if (Float.class.isAssignableFrom(type)) {
                                field.set(obj, Float.valueOf(defVal));
                            } else if (Short.class.isAssignableFrom(type)) {
                                field.set(obj, Short.valueOf(defVal));
                            } else if (Double.class.isAssignableFrom(type)) {
                                field.set(obj, Double.valueOf(defVal));
                            } else if (Integer.class.isAssignableFrom(type)) {
                                field.set(obj, Integer.valueOf(defVal));
                            } else if(Long.class.isAssignableFrom(type)) { field.set(obj, Long.valueOf(defVal)); }}else if (Boolean.class.isAssignableFrom(type)){
                            field.set(obj,Boolean.valueOf(defVal));
                        }else if (Character.class.isAssignableFrom(type)){
                            field.set(obj,Character.valueOf(defVal.charAt(0))); }}catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    Copy the code
    1. The Main method
    public class Main {
        public static void main(String[] args) {
            Person person = newPerson(); ParamProcessor.setDefalutValue(person); System.out.println(person); }} output: Person{name='ddb12138', age=13, money=20.2, man=true, lastName=无}
    Copy the code