how to pass different enum types to a method?
I have a method which takes an enum and uses it in some fashion. The issue is that I have many different enum types and am not what acceptable practice is to pas开发者_高级运维s an enum to a method.
I'm assuming that you mean you have a bunch of different enum classes that mean separate things, and that you want to pass them into one method.
To do that, use a marker interface:
public interface SpecialEnumType {
}
then:
public enum MySpecialEnumType implements SpecialEnumType {
...
}
public enum AnotherSpecialEnumType implements SpecialEnumType {
...
}
Now your method will accept a parameter of type SpecialEnumType
:
public doSomething(SpecialEnumType specialEnumType) {
...
}
Having done that, you can do:
obj.doSomething(MySpecialEnumType.SomeThing);
obj.doSomething(AnotherSpecialEnumType.SomethingElse);
In general, it's perfectly alright to use an enum as a parameter type for a method argument.
UPDATE
I've used this pattern while integrating with third-party API's. For example, a little while ago I had to integrate with different shipping providers. To do this, I provided a general interface that allowed the developer to send in shipping information (like the addresses, packages, weights, packing options, etc.). If you wanted to implement integration with a new provided, all you needed to do was implement the interface.
Now each shipping provider had its own set of options. Before using marker interfaces, I had a single enum which contained all the options (of all the different shipping providers). This is obviously hard to maintain. But I couldn't split the enums into different classes because the interface specified a specific type of enum for the method arguments.
Using a marker interface, I was able to get around this problem. I created an interface called ShippingProviderOption
. Then for each provider, I extended the interface and created an enum, with the specific options for that provider. This way I was able to separate out the options, but still present a common interface.
As far as code is concerned (greatly simplified and somewhat contrived, for demonstration purposes):
public interface ShippingProviderOption {
}
public enum UPSOption implements ShippingProviderOption {
...
}
public enum FedexOption implements ShippingProviderOption {
...
}
public interface ShippingProvider {
public ShippingResponse ship(ShippingProviderOption option);
}
public class UPSProvider implements ShippingProvider {
@Override
public ShippingResponse ship(ShippingProviderOption option) {
if(option == UPSOption.PackageType) {
...
}
}
}
public class FedexProvider implements ShippingProvider {
@Override
public ShippingResponse ship(ShippingProviderOption option) {
if(option == FedexOption.PickupType) {
...
}
}
}
Now in my actual implementation, I have a few methods in the marker interface. So it doesn't really even have to be a marker interface; it can contain methods.
精彩评论