Reputation: 10815
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
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
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