简体   繁体   中英

Java Bounded Type Parameter in Enum

I am trying to create following enum.

public enum MyEnum{
     LEAD {
       @Override 
       public boolean isValid(Lead lead) { //compile error, asks to retain type as T
       }
     },
     TASK {
       @Override 
       public boolean isValid(Task task) { //compile error, asks to retain type as T
       }
     };

     public abstract <T extends SObject> boolean isValid(T  object);
}

Lead and Task classes both extend SObject . My intention is to basically let clients be able to use MyEnum.LEAD.isValid(lead) or MyEnum.TASK.isValid(task) . Compiler shouldn't allow to pass other types.

Could someone help in understand why this is happening.

Thanks

You need to override the generic method with the same generic method. If you want to do what you are asking you need a generic class - which an enum cannot be.

The point being that I refer to the enum by the class reference - ie

final MyEnum myenum = MyEnum.LEAD;

Now if I call myenum.isValid() I should be able to call it with any SObject as defined by your abstract method.
The generic method definition that you have doesn't actually do anything. All it is doing is capturing the type of the passed in SObject and storing it as T . A generic method is commonly used to tie together types of parameters, for example

<T> void compare(Collection<T> coll, Comparator<T> comparator);

Here we do not care what T actually is - all we require is that the Comparator can compare the things that are in the Collection .

What you are thinking of is a generic class, something like:

interface MyIface<T> {
    boolean isValid(T  object);
}

And then

class LeadValid implements MyIface<Lead> {
    public boolean isValid(Lead object){}
}

You see the difference is that you would have a MyIface<Lead> - you would have to declare the type of MyIface . In the enum case you only have a MyEnum .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM