Enumeration, annotation, reflection

Keywords: Java IntelliJ IDEA intellij-idea

enumeration

Format of enumeration

Permission modifier enum enumeration name{  

            Example 1, example 2, example 3, example 4;

}

package com.meiju;

public enum Level2 {

    LOW(1),MEDIUM(50),HIGH(100);

    private int levelValue;

    private  Level2(int levelValue){
        this.levelValue=levelValue;
    }

    public int getLevelValue() {
        return levelValue;
    }

    public void setLevelValue(int levelValue) {
        this.levelValue = levelValue;
    }
}

Enumeration method

package com.meiju;

public class Demo {
    public static void main(String[] args) {
        System.out.println(Level.LOW.getLevelValue());
        //compareTo compares the order of the object with the specified object
        System.out.println(Level3.LOW.compareTo(Level3.HIGH));
        System.out.println(Level3.LOW.compareTo(Level3.MEDIUM));
        //Returns the name of this enumeration constant and declares it in its enumeration object
        System.out.println(Level2.LOW.name());
        System.out.println(Level2.LOW.toString());
        //Returns the ordinal of this enumeration constant (position in the enumeration, starting at 0)
        System.out.println(Level2.LOW.ordinal());

        
        Level2 X = Enum.valueOf(Level2.class, "HIGH");
        System.out.println(X.name());
    }

    public static void haha(Level2 l){
        switch (l){
            case LOW:break;
            case HIGH:break;
        }
    }
}

Implementation of enumeration interface

package com.meiju;

public class Demo {
    public static void main(String[] args) {
        System.out.println(Level.LOW.getLevelValue());
        //compareTo compares the order of the object with the specified object
        System.out.println(Level3.LOW.compareTo(Level3.HIGH));
        System.out.println(Level3.LOW.compareTo(Level3.MEDIUM));
        //Returns the name of this enumeration constant and declares it in its enumeration object
        System.out.println(Level2.LOW.name());
        //Returns the name of the enumeration object
        System.out.println(Level2.LOW.toString());
        //Returns the ordinal of this enumeration constant (position in the enumeration, starting at 0)
        System.out.println(Level2.LOW.ordinal());


        Level2 X = Enum.valueOf(Level2.class, "HIGH");
        System.out.println(X.name());

        Level3.LOW.show();
    }

    public static void haha(Level2 l){
        switch (l){
            case LOW:break;
            case HIGH:break;
        }
    }
}

matters needing attention

Once an enumeration is defined, it is best not to attempt to modify the values in it unless modification is necessary.

Enumeration class inherits java.lang.Enum class instead of Object class by default

An enumeration class cannot have subclasses because its enumeration class is modified by final by default

There can only be private constructors

When enumerations are used in switch, constant names are used directly without carrying class names

The name attribute cannot be defined because it comes with a name attribute

Do not provide set methods for attributes in enumeration classes, which is inconsistent with the original design intention of enumeration.

annotation

Classes, methods, variables, parameters and packages in ava language can be annotated. Unlike annotations, Java annotations can obtain annotation content through reflection. When the compiler generates class files, annotations can be embedded into bytecode. Java virtual machine can retain annotation content and obtain annotation content at run time. Of course, it also supports custom Java annotations.

It is mainly used for: compiling format checking, parsing in reflection, generating help documents, tracking code dependencies

Built in annotation

@Override: override*

@Deprecated: discarded*

Functional interface: functional interface*

SuppressWarnings: suppresses compile time warnings* (all suppresses all warnings, boxing suppresses warnings during boxing and unpacking operations, cast suppresses warnings related to mapping, DEP Ann suppresses warnings with comments enabled, depreciation suppresses warnings of expired methods, fallthrough suppresses warnings that breaks are missing in the switch, finally suppresses warnings that are not returned by the finally module, and high suppresses warnings of local variables relative to hidden variables Advise that incomplete switch ignores incomplete switch statements, nls ignores characters in non nls format, null ignores the operation on null, rawtypes ignores that no corresponding type is specified when using generics, restriction suppresses warnings that dissuade or prohibit reference, serial ignores that it is not declared in the serializable class, and the serialVersionUID variable static access suppresses incorrect static access State access mode warning, synthetic access suppresses the warning that subclasses do not access internal classes according to the optimal method, unchecked suppresses the warning that type checking operation is not performed, unqualified field access suppresses the warning of domains without access permission, and unused suppresses the warning of unused code)

package com.zhuJie;

public class Demo1 {
    public static void main(String[] args) {
        Person p = new Person();
        p.setAge(18);
        p.setAge2(18);
        @SuppressWarnings("all")
        Person o = new Person();
    }
    @Override
    public String toString() {
        return super.toString();
    }
}
@SuppressWarnings("all")
class Student{

}

class Person{
    private int age ;

    @SuppressWarnings("all")
    public int getAge() {
        return age;
    }

    /**
     * This method is obsolete, please use setage2
     * @param age
     */
    @Deprecated
    public void setAge(int age) {
        this.age = age;
    }

    public void setAge2(int age){
        if (age>120 || age<0){
            throw new RuntimeException("Unreasonable age");
        }
        this.age =age;
    }
}

Meta annotation

package com.zhuJie;

import com.sun.jdi.Value;

import java.lang.annotation.*;

@MyAnnotation(value={"with","too","particle"},num = 1)
public class Demo2 {
}

//Are annotations included in the document
@Documented
//Use type
@Target({ElementType.TYPE,ElementType.METHOD})
//Save policy
@Retention(RetentionPolicy.RUNTIME)
//Can inherit
@Inherited
@interface MyAnnotation{
//Default to declare the default value of the parameter
//An annotation element must have a value. When defining an annotation element, we often use an empty string and 0 as the default value.
    String[] value() default {"Zhang San","Li Si"};
    int num() default 0;
}

Class   And loading mode

package com.fanShe;

public class Person {

}
package com.fanShe;

public class Demo1 {
    public static void main(String[] args) throws ClassNotFoundException {
        //The first way is to load classes through package name. class name. class
        Class<Person> c1= Person.class;
        System.out.println(c1);

        //The second way is to obtain class information through class objects
        Person p  = new Person();
        Class<Person> c2 = (Class<Person>) p.getClass();
        System.out.println(c2);
        System.out.println(c1==c2);

        //The third way
        Class<Person> c3 = (Class<Person>) Class.forName("com.fanShe.Person");
        System.out.println(c3);
        System.out.println(c1==c2 || c1==c3);
    }

    public static Class getClass2(String className) throws ClassNotFoundException {
        return Class.forName(className);
    }
}

Construction method in reflection

package com.fanShe;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Demo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Person> pClass = (Class<Person>) Class.forName("com.fanShe.Person");
        //No parameter constructor found
        Constructor<Person> c1 = pClass.getConstructor();
        //Use the parameterless construction method to create objects
        Person p = c1.newInstance();
        System.out.println(p);

        //Find the constructor containing String name and int age
        Constructor<Person> c2 = pClass.getConstructor(String.class, int.class);
        //Creating objects using the full parameter construction method
        Person p1 = c2.newInstance("Zhang San",11);
        System.out.println(p1);


        Constructor<Person> c3 = pClass.getDeclaredConstructor(String.class);
        //Ignore access check (can access any permissions)
        c3.setAccessible(true);
        Person p2 = c3.newInstance("prince");
        System.out.println(p2);

    }
}

Posted by zulfiboy on Mon, 06 Dec 2021 22:42:21 -0800