Java Enums类相关方法调用示例

x33g5p2x  于2021-08-19 转载在 Java  
字(7.6k)|赞(0)|评价(0)|浏览(130)

在本教程中,我们将学习基础知识,并通过大量实例在实时项目中创建一个Enum数据类型。

我们将学到什么?

  1. 枚举基础知识
  2. 在一个类中定义一个枚举
  3. 在if-else if语句中使用枚举
  4. 在switch语句中使用枚举
  5. 如何对一个枚举进行迭代?
  6. 实时项目中的枚举类型实例
  7. Enum可以实现接口,Enum可以嵌套。

1. 枚举基础知识

枚举类型是一种特殊的数据类型,它可以让一个变量成为一组预定义的常量。该变量必须等于为其预定义的值之一。常见的例子包括罗盘方向(北、南、东、西的值)和一周的天数。

下面的类图显示了Enum类型提供的方法或API的列表。

Java Enum类型的关键点

  • 枚举提高了类型的安全性
  • 枚举类型的字段名都是大写字母。
  • 枚举可以很容易地在开关中使用
  • 枚举可以被遍历
  • 枚举可以有字段、构造函数和方法
  • 我们不能创建enum的实例,因为enum类型的构造函数是私有的(如果你不声明私有,编译器会在内部创建私有构造函数)。
  • 我们可以在枚举中编写抽象的方法,我们可以为其提供一个实现。
  • 枚举可以实现许多接口,但不能扩展任何类,因为它在内部扩展了Enum类 在Java编程语言中,你通过使用枚举关键字定义一个枚举类型。例如,你会指定一个星期的天数的枚举类型为。
public enum Day {
 SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY;
}

让我们写一段源代码来使用上面定义的Day枚举。在实际项目中,我们基本上使用switch语句来比较枚举值,如

public class DayEnumTest {
 Day day;
 
 public DayEnumTest(){
  
 }
 
 public DayEnumTest(Day day) {
        this.day = day;
    }
    
    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;
                    
            case FRIDAY:
                System.out.println("Fridays are better.");
                break;
                         
            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best.");
                break;
                        
            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }
    
    public void mapEnum(Day day){
     switch (day) {
      case MONDAY:
             System.out.println("This is Monday");
             break;
                 
         case FRIDAY:
             System.out.println("This is Friday");
             break;
                      
         case SATURDAY: case SUNDAY:
             System.out.println("Weekends are best.");
             break;
                     
         default:
             System.out.println("Midweek days");
             break;
     }
    }
    
    public static void main(String[] args) {
        final DayEnumTest firstDay = new DayEnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        final DayEnumTest thirdDay = new DayEnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        final DayEnumTest fifthDay = new DayEnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        final DayEnumTest sixthDay = new DayEnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        final DayEnumTest seventhDay = new DayEnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
        
        final DayEnumTest dayEnumTest = new DayEnumTest();
        dayEnumTest.mapEnum(Day.MONDAY);
    }
}

其输出结果是

Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.
This is Monday

2. 在一个类中定义一个枚举

例子。在一个类中定义枚举类型的例子。

3. 在if-else if语句中使用Enum

例子。如何在if-else if 语句中使用Enums。

public class EnumInIfStatement {

   public String enumInIf(Days day) {
       if(day == Days.SUNDAY) {
           return "Its Sunday :-)";
       }else if (day == Days.MONDAY) {
           return "Its Monday :/*--(";
       }else if (day == Days.TUESDAY) {
           return "Its Tuesday :/*-(";
       }else if (day == Days.WEDNESDAY) {
           return "Its Wednesday :/*(";
       }else if (day == Days.THURSDAY) {
           return "Its Thursday :)";
       }else if (day == Days.FRIDAY) {
           return "Its Friday ;-D";
       }else {
           return "Its Saturday :=D";
       }
   }
}

4. 在switch语句中使用Enums

例子。如何在switch语句中使用Enums。

public class EnumInSwitchStatement {
   public String enumInSwitch(Days day) {
       switch(day) {
           case SUNDAY:
               return "Its Sunday!!";
           case MONDAY:
               return "Its Monday";
           case TUESDAY:
               return "Its Tuesday";
           case WEDNESDAY:
               return "Its Wednesday";
           default:
               return "Rest of the week....";
       }
   }
}

5. 如何对一个枚举进行迭代?

例子。如何在一个枚举上进行迭代的例子。

import java.util.ArrayList;

public class EnumIteration {
   enum Days{
       SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
   }

   public ArrayList<String> enumIteration() {
       Days[] days = Days.values();
       ArrayList<String> stringDay = new ArrayList<String>();
       for (Days day : days) {
           stringDay.add(day.toString());
       }
       return stringDay;
   }
}

6. 实时项目中的枚举类型示例

假设我们在项目中使用多个数据库,如MySQL和Postgres。

为了与数据库建立连接,我们需要注册Driver,这些Driver名称是恒定的或固定的。
让我们写一个Enum来使Driver的名字预定义。

public enum DbType {
    MYSQL("com.mysql.jdbc.Driver"), POSTGRESQL("org.postgresql.Driver");

    private final String driverClassName;

    private DbType(final String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getDriverClassName() {
        return driverClassName;
    }
}

在真实的项目中,我们为一些实体(如ProjectEntity)维护一个状态,它的状态可以是活动或不活动。这方面的枚举是:

public enum ProjectStatus {
  ACTIVE, INACTIVE
}

7. Enum可以实现接口,Enum可以嵌套。

完整的例子来证明Enum可以实现接口和Enum可以嵌套。

让我们创建一个StatusType接口,该枚举实现了。

public interface StatusType {

    //*/*
/* Get the associated status code.
/*
/* @return the status code.
/*/
    public int getStatusCode();

    //*/*
/* Get the class of status code.
/*
/* @return the class of status code.
/*/
    public Status.Family getFamily();

    //*/*
/* Get the reason phrase.
/*
/* @return the reason phrase.
/*/
    public String getReasonPhrase();
}

让我们创建一个枚举Status,它实现了StatusType接口,也包含嵌套的枚举。

public enum Status implements StatusType {

    OK(200, "OK"),
    CREATED(201, "Created"),
    ACCEPTED(202, "Accepted"),
    NO_CONTENT(204, "No Content"),
    RESET_CONTENT(205, "Reset Content"),
    PARTIAL_CONTENT(206, "Partial Content"),
    MOVED_PERMANENTLY(301, "Moved Permanently"),
    FOUND(302, "Found"),
    SEE_OTHER(303, "See Other"),
    NOT_MODIFIED(304, "Not Modified"),
    USE_PROXY(305, "Use Proxy"),
    TEMPORARY_REDIRECT(307, "Temporary Redirect"),
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    PAYMENT_REQUIRED(402, "Payment Required"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
    NOT_ACCEPTABLE(406, "Not Acceptable"),
    PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),
    REQUEST_TIMEOUT(408, "Request Timeout"),
    CONFLICT(409, "Conflict"),
    GONE(410, "Gone"),
    LENGTH_REQUIRED(411, "Length Required"),
    PRECONDITION_FAILED(412, "Precondition Failed"),
    REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
    REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),
    UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
    REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"),
    EXPECTATION_FAILED(417, "Expectation Failed"),
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    NOT_IMPLEMENTED(501, "Not Implemented"),
    BAD_GATEWAY(502, "Bad Gateway"),
    SERVICE_UNAVAILABLE(503, "Service Unavailable"),
    GATEWAY_TIMEOUT(504, "Gateway Timeout"),
    HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported");
    private final int code;
    private final String reason;
    private final Family family;

    //*/*
/* An enumeration representing the class of status code. Family is used
/* here since class is overloaded in Java.
/*/
    public enum Family {

        //*/*
/* {@code1xx} HTTP status codes.
/*/
        INFORMATIONAL,
        //*/*
/* {@code2xx} HTTP status codes.
/*/
        SUCCESSFUL,
        //*/*
/* {@code3xx} HTTP status codes.
/*/
        REDIRECTION,
        //*/*
/* {@code4xx} HTTP status codes.
/*/
        CLIENT_ERROR,
        //*/*
/* {@code5xx} HTTP status codes.
/*/
        SERVER_ERROR,
        //*/*
/* Other, unrecognized HTTP status codes.
/*/
        OTHER;

        //*/*
/* Get the response status family for the status code.
/*
/* @param statusCode response status code to get the family for.
/* @return family of the response status code.
/*/
        public static Family familyOf(final int statusCode) {
            switch (statusCode / 100) {
                case 1:
                    return Family.INFORMATIONAL;
                case 2:
                    return Family.SUCCESSFUL;
                case 3:
                    return Family.REDIRECTION;
                case 4:
                    return Family.CLIENT_ERROR;
                case 5:
                    return Family.SERVER_ERROR;
                default:
                    return Family.OTHER;
            }
        }
    }

    Status(final int statusCode, final String reasonPhrase) {
        this.code = statusCode;
        this.reason = reasonPhrase;
        this.family = Family.familyOf(statusCode);
    }

    //*/*
/* Get the class of status code.
/*
/* @return the class of status code.
/*/
    @Override
    public Family getFamily() {
        return family;
    }

    //*/*
/* Get the associated status code.
/*
/* @return the status code.
/*/
    @Override
    public int getStatusCode() {
        return code;
    }

    //*/*
/* Get the reason phrase.
/*
/* @return the reason phrase.
/*/
    @Override
    public String getReasonPhrase() {
        return toString();
    }

    //*/*
/* Get the reason phrase.
/*
/* @return the reason phrase.
/*/
    @Override
    public String toString() {
        return reason;
    }

    //*/*
/* Convert a numerical status code into the corresponding Status.
/*
/* @param statusCode the numerical status code.
/* @return the matching Status or null is no matching Status is defined.
/*/
    public static Status fromStatusCode(final int statusCode) {
        for (final Status s : Status.values()) {
            if (s.code == statusCode) {
                return s;
            }
        }
        return null;
    }
}

相关文章