Sarah Szabo
Sarah Szabo

Reputation: 10815

How To Implement A Method Signature That Will Return a Concrete Type of an Enum?

I want to create a method that will return one of four types from an enum. So if someone wants a filter of SCAN_RANK_GROUPS, how can I get the return type of the method to be Rank, or if somebody wants SCAN_MEMBERS it will return Member. How can I go about doing this?

public <T> T scanTemporaryStorage(ScanFilters filter) {
    return (T) filter.performOperation();
}

public enum ScanFilters {

    SCAN_RANK_GROUPS {
                @Override
                public <Rank> Rank performOperation() {
                }
            },
    SCAN_MEMBERS {

                @Override
                public <Member> Member performOperation() {
                }

            };

    public abstract <T> T performOperation();

}

Upvotes: 3

Views: 396

Answers (2)

Anubian Noob
Anubian Noob

Reputation: 13596

This isn't possible the way it's done. My suggestion is to create a superclass Scannable for both Rank and Member, and use that:

public Scannable scanTemporaryStorage(ScanFilters filter) {
    return filter.performOperation();
}

public enum ScanFilters {

    SCAN_RANK_GROUPS {
                @Override
                public Scannable performOperation() {
                }
            },
    SCAN_MEMBERS {

                @Override
                public Scannable performOperation() {
                }
            };

    public abstract Scannable performOperation();

}

The parent class Scannable will have all the shared methods:

public abstract class Scannable {

    // have all the methods in Rank and Member
}

And have your classes extends it.

public class Rank extends Scannable

public class Member extends Scannable

Upvotes: 3

etherous
etherous

Reputation: 709

From what I understand about Java, the only way to do this is to specify a return type common to all those types, or, if there is no common type, to return an instance of Object. You can then use instanceof to determine which type was returned

Edit: Well, I shouldn't say that's the only way

public static enum ExampleEnum
{
    A{
        @Override
        public Integer returnA ()
        {
            return 42;
        }
    },
    B{
        @Override
        public String returnB ()
        {
            return "Foo";
        }
    }
    ;
    public Integer returnA ()
    {
        return null;
    }
    public String returnB ()
    {
        return null;
    }
}

Upvotes: 1

Related Questions