Enumeration class & annotation & Reflection

Posted by perry789 on Sun, 25 Aug 2019 12:00:27 +0200

What is an enumeration class?

Enumeration classes are special classes that optimize the definition of fixed objects.

In other words, when you need instances of a class to be one or more and relatively fixed, use enumerated classes. (Enumeration class extensible)


Class instances are relatively fixed with dates, objectively unchanged numbers, and so on.

enum WorkDay
{
    MONDAY, THUEDAY, WEDNESDAY , THURSDAY , FRIDAY;
}


public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");

        WorkDay workDay;

        workDay=WorkDay.MONDAY;   //Workday values for WorkDay instantiation are limited between Monday and Friday

//      workDay=3; // Compile Error Reporting

        WorkDay []workDays = WorkDay.values();  //Returns an array of objects of enumeration type

        for(int i =0;i<workDays.length;i++)
        {
            System.out.println(workDays[i]);
        }



        /**
         * Singleton pattern is a special case of enumeration class. The requirement of singleton pattern is that a class can only have one instance object.
         * The use of enumerated classes is to fix one or more of their objects when defining classes
         *
         * The characteristics of enumeration classes:
         *  - Type safety (the definition of enumeration classes is fixed)
         *  - Objects of enumerated classes automatically add private static final
         *  - To some extent, the enumeration class can add a set of constants or objects to extract the main program, which reduces the coupling between classes. It's also easier to extend enumeration class templates
         */

    }
}

annotation

Annotation is actually a special tag in the code, which can be read at compilation, class loading, runtime and processed accordingly.

Annotations are essentially an interface and a set of key-value pairs that reflect and proxy certain behaviors.


[Frame = Annotation + Reflection + Design Patterns. ]

/**
 * @author shkstart
 * @version 1.0
 *
 */
public class Main {
    /**
     * The main method of the program, the entrance of the program
     * @param args String[] Command line parameters
     */

    @SuppressWarnings("unused")  //Suppression of compiler warnings
    int a = 10;

    @Deprecated     //Used to indicate that the modified elements (classes, methods, etc.) are obsolete. Usually because the modified structure is dangerous or there are better options
    public void print(){
        System.out.println("Outdated methods");
    }
    @Override       //Restrict override of parent methods, and this annotation can only be used for methods
    public String toString() {
        return "Rewriting toString Method()"; }
    public static void main(String[] args) {
    }
    /**
     * The Method of Finding the Area of a Circle
     * @param radius double Radius value
     * @return double Area of a circle
     */
    public static double getArea(double radius){
        return Math.PI * radius * radius; }
}

reflex

What is reflection?

Reflection mechanism allows the program to obtain the internal information of any class at runtime by means of Reflection API, and can directly manipulate the internal attributes and methods of any object. (Supreme Authority)



Object class

package java.lang;

public class Object {

   private static native void registerNatives();
    static {
        registerNatives();
    }


    public final native Class<?> getClass();

    public native int hashCode();

    public boolean equals(Object obj) {
        return (this == obj);
    }

    protected native Object clone() throws CloneNotSupportedException;


    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }


    public final native void notify();


    public final native void notifyAll();


    public final native void wait(long timeout) throws InterruptedException;

 
    public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos > 0) {
            timeout++;
        }

        wait(timeout);
    }

    
 
    public final void wait() throws InterruptedException {
        wait(0);
    }


    protected void finalize() throws Throwable { }
}

There is one such method.

public final native Class<?> getClass();


Get an instance of the Class class

  • If specific class es are known, the method is the most secure and reliable, and the program performance is the highest.

  • Given an instance of a class, call the getClass() method of that instance to get the Class object

  • The full class name of a class is known, and the class can be obtained through the static method forName() of the Class class under the class path, possibly throwing a ClassNotFoundException.

    Class test  = String.class;
    
    
    Class test01 = "Hello World!".getClass();
    
    
    Class test02 = Class.forName("java.lang.String");  //Throw an exception

All classes inherit Object, so String.class returns an instance of the class.

There is a forName method in the Class class, and the return value is also Class:

Get class information, call class attributes and methods

package test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Work {
    private String name;
    private Integer age;
    private String gender;
    private String job;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    @Override
    public String toString() {
        return "Work{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", job='" + job + '\'' +
                '}';
    }
}


public class ReflectWork
{

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {


        Class classWork = Class.forName("test.Work");


        System.out.println(" /// Get all method information“
        );


        Method []methods= classWork.getDeclaredMethods();

        for (Method m:methods) {
            System.out.println(m.toString());

        }

        System.out.println("  //Get all member attribute information ";

        Field[] field=classWork.getDeclaredFields();
        for(Field f:field){
            System.out.println(f.toString());

            f.setAccessible(true);  //Cancel access control for private attributes of classes

            System.out.println(f.getName().toString());
        }


        System.out.println("//Initialize by reflection.
        Work reflectWork = (Work) classWork.newInstance();
        reflectWork.setAge(22);
        reflectWork.setJob("Dev");
        Work work = reflectWork;

        System.out.println(work);




    }
}

Topics: Java Attribute