Home > Enterprise >  Can you make Java enums over Classes?
Can you make Java enums over Classes?

Time:03-24

I am not a Java programmer, but I need to write some Java code, and I have been reading about Java enums, that Java enum class is a special type of class which were introduced in Java 5 to replace int constants. My question is, since there are two types one primitive, int and the other Integer which is a class, is it possible to create enums out of classes? Can I have the following for instance?

enum ClassEnum {
 Integer,
 Double,
 MyClass
}

The reason I want to do it is because I have 3-4 classes that I need to switch on, a dispatch certain methods based on what class I get in my switch. All N classes that I will be switching over have their own structure, and as a result needs to be handled differently based on what type they are. They are all part of one common abstract class though.

CodePudding user response:

If you are using latest version of the Java, you have lot of options with Sealed Classes and Pattern Matching capability.

Following is one more option that might work in your context. But this approach not recommended.

public enum ClassType {
  NONE(None.class), // Could not determine.
  INTEGER(Integer.class),
  CHAR(Character.class),
  LONG(Long.class),
  FLOAT(Float.class),
  DOUBLE(Double.class),
  EMPLOYEE(Employee.class),
  ETC(Etc.class);

  private Class aClass;

  private ClassType(Class aClass) {
    this.aClass = aClass;
  }

  public static ClassType getClassTypeByClass(Class aClass) {
   return Arrays.stream(values()).filter(entry -> entry.aClass == aClass).findFirst().orElse(NONE);
  }
}

class Employee {}
class Etc {}
class None {}

Following sample code for validating:

ublic class ClassTypeMain {

  public static void main(String[] args) {
    determineType(ClassType.getClassTypeByClass(Integer.class));
    determineType(ClassType.getClassTypeByClass(Etc.class));
    determineType(ClassType.getClassTypeByClass(String.class));
    determineType(ClassType.getClassTypeByClass(Employee.class));
  }

  private static void determineType(ClassType classType) {
    switch(classType) {
      case ETC: System.out.println(" I am ETC");
        break;
      case INTEGER: System.out.println(" I am INT");
        break;
      case NONE: System.out.println(" Could not determine type");
        break;
      default: System.out.println(" Something else ");
    }

  }

CodePudding user response:

Considering the description of your problem, you might be looking for the Command pattern. As you mentioned that all classes have a common abstract class, you can add an abstract method (e.g. execute()) in this class and have different implementations in each subclass. Then you won't need to use any switch, just call the execute() method and the specific logic will be executed according to the subclass. Please check the reference I added here, they explain very well with an example.

  • Related