《onjava进阶卷》01枚举类型1-4

81 阅读2分钟

1、枚举的基本特性

如何定义枚举、遍历枚举、字符串转枚举类型

// 定义枚举  
// 灌木丛{地面,爬行,悬挂}  
enum Shrubbery {GROUND, CRAWLING, HANGING}  
  
/**  
 * 枚举类型的基本特性  
 */  
public class EnumClass {  
    public static void main(String[] args) {  
        // 遍历枚举  
        for (Shrubbery s : Shrubbery.values()) {  
            // 顺序  
            System.out.println(s + " ordinal: " + s.ordinal());  
            System.out.print(s.compareTo(Shrubbery.CRAWLING) + " ");  
            System.out.print(s.equals(Shrubbery.CRAWLING) + " ");  
            System.out.println(s == Shrubbery.CRAWLING);  
            System.out.println(s.getDeclaringClass());  
            System.out.println(s.name());  
            System.out.println("*******************");  
        }  
  
        // 字符串 -> 枚举  
        // 根据字符串名生成一个枚举值  
        for (String s : "HANGING CRAWLING GROUND".split(" ")) {  
            Shrubbery shrub = Enum.valueOf(Shrubbery.class, s);  
            System.out.println(shrub);  
        }  
    }  
}

静态导入枚举类型 定义

public enum SpicinessEnum {  
    NOT, MILD, MEDIUM, HOT, FLAMING  
}

静态导入

/**  
 * 静态导入枚举类型  
 */  
public class Burrito2 {  
    SpicinessEnum degree;  
  
    public Burrito2(SpicinessEnum degree) {  
        this.degree = degree;  
    }  
  
    @Override  
    public String toString() {  
        return "Burrito is " + degree;  
    }  
  
    public static void main(String[] args) {  
        System.out.println(new Burrito2(NOT));  
        System.out.println(new Burrito2(MEDIUM));  
        System.out.println(new Burrito2(HOT));  
    }  
}

2、在枚举类型中增加自定义方法

/**  
 * 在枚举类中自定义自己的方法  
 */
public enum OzWitch {  
    WEST("Miss Gulch, aka the Wicked Witch of the West"),  
    NORTH("Glinda, the Good Witch of the North"),  
    EAST("Wicked Witch of the East, wearer of the Ruby Slippers, crushed by Dorothy's house"),  
    SOUTH("Good by inference, but missing");  
  
    private String description;  
  
    private OzWitch(String description) {  
        this.description = description;  
    }  
  
    public String getDescription() {  
        return this.description;  
    }  
  
    public static void main(String[] args) {  
        for (OzWitch witch : OzWitch.values()) {  
            System.out.println(witch + ": " + witch.getDescription());  
        }  
    }  
}
import java.util.stream.Stream;  
  
/**  
 * 重载枚举类型中的方法  
 */
public enum SpaceShip {  
    SCOUT, CARGO, TRANSPORT, CRUISER, BATTLESHIP, MOTHERSHIP;  
  
    @Override  
    public String toString() {  
        String id = name();  
        String lower = id.substring(1).toLowerCase();  
        return id.charAt(0) + lower;  
    }  
  
    public static void main(String[] args) {  
        Stream.of(values()).forEach(System.out::println);  
    }  
}

3、在switch语句中使用枚举

enum Signal {GREEN, YELLOW, RED}  
  
/**  
 * 在switch语句中使用枚举  
 */
public class TrafficLight {  
    Signal color = Signal.RED;  
  
    public void change() {  
        switch (color) {  
            case RED:  
                color = Signal.GREEN;  
                break;  
            case GREEN:  
                color = Signal.YELLOW;  
                break;  
            case YELLOW:  
                color = Signal.RED;  
                break;  
        }  
    }  
  
    @Override  
    public String toString() {  
        return "The traffic light is " + color;  
    }  
  
    public static void main(String[] args) {  
        TrafficLight t = new TrafficLight();  
        for (int i = 0; i < 7; i++) {  
            System.out.println(t);  
            t.change();  
        }  
    }  
}

4、values()方法的神秘之处

  
import onjava.OSExecute;  
  
import java.lang.reflect.Method;  
import java.lang.reflect.Type;  
import java.util.Set;  
import java.util.TreeSet;  
  
enum Explore {HERE, THERE}  
  
/**  
 * values()方法的神秘之处  
 * 1、所有枚举类型都继承自Enum  
 * 2、Enum类中并没有values()方法  
 * 3、枚举类型中的values()方法是由编译器添加的静态就去  
 * 4、枚举类被限定为final,无法被继承  
 */
public class Reflection {  
    public static Set<String> analyze(Class<?> enumClass) {  
        System.out.println("______Analyzing " + enumClass + "______");  
        System.out.println("Interfaces:");  
        for (Type t : enumClass.getGenericInterfaces()) {  
            System.out.println(t);  
        }  
        System.out.println("Base: " + enumClass.getSuperclass());  
        System.out.println("Methods: ");  
        Set<String> methods = new TreeSet<>();  
        for (Method m : enumClass.getMethods()) {  
            methods.add(m.getName());  
        }  
        System.out.println(methods);  
        return methods;  
    }  
  
    public static void main(String[] args) {  
        Set<String> exploreMethods = analyze(Explore.class);  
        Set<String> enumMethods = analyze(Enum.class);  
        System.out.println("Explore.containsAll(Enum)? " + exploreMethods.removeAll(enumMethods));  
        System.out.println(exploreMethods);  
        // 反编译enum,注意路径  
        OSExecute.command("javap -cp target/classes onjava.advance.ch01.sec04.Explore");  
    }  
}