I'm attempting to create an enum whose constructor accepts an object whose base class is a generic class.
I seem to be unable to fetch the underlying generic type from within the enum however, Object gets returned instead of T.
Is there a way to do this?
abstract public class Field<T> {
abstract public T get();
}
public class IntegerField extends Field<Integer> {
public Integer get() {
return 5;
}
}
public class StringField extends Field<String> {
public String get() {
return "5";
}
}
public enum Fields {
INTEGER (new IntegerField()),
STRING (new StringField());
private final Field<?> field; // <<--- I can't have Field<T>, enum's can't be generic. :(
<T> Fields(Field<T> field) {
this.field = field;
}
public <T> T get() {
return field.get(); // <<--- Returns Object, not T
}
}
The issue is that enums can't be generically typed so even if you cast that get call ((T) field.get()) you won't have type safety because it will agree with any assignment (you could compile this successfully for instance: boolean b = Fields.INTEGER.get()).
Just use constants instead:
public final class Fields {
public static final Field<Integer> INTEGER = new IntegerField();
public static final Field<String> STRING = new StringField();
}
Why do you think an enum is preferable to this?
public final class Fields {
public static final Field<Integer> INTEGER = new IntegerField();
public static final Field<String> STRING = new StringField();
//private ctor
}
or if you prefer
public final class Fields {
public static Field<Integer> integerField() {
return new IntegerField();
}
public static Field<String> stringField() {
return new StringField();
}
//private ctor
}
Why would I want to call Fields.INTEGER.get() when I can just use Fields.INTEGER?
In my generic class I need to restrict type parameter to Integer OR String. Is there a way to achieve this? I cannot use T extends SomeClass to limit types, because common parent is just Object...
update
public abstract class MyClass<T>{
private T value;
public T getValue(){
return value;
}
}
I'd like the value type to be a String or an Integer and I need to use the same method to get it (not getIntValue() + getStringValue() )
This doesn't seem to help...
If I were you, I would overload two methods:
public void withInteger(Integer param) { .. }
public void withString(String param) { .. }
Note that there's no reason to use something like T extends String, because both String and Integer are final and can't be subclassed.
Just made your class ctor private and pass through a factory method to create implementation; type restriction is not bounded to MyClass but via factory.
class MyClass<T> {
private T value;
MyClass(T value) { this.value = value; }
public T getValue() { return value; }
}
class MyClassFactory {
public final static MyClass<Integer> createInteger(Integer i) {
return new MyClass<Integer>(i);
}
}
I have an object hierarchy that increases in complexity as the inheritance tree deepens. None of these are abstract, hence, all of their instances serve a, more or less sophisticated, purpose.
As the number of parameters is quite high, I would want to use the Builder Pattern to set properties rather than code several constructors. As I need to cater to all permutations, leaf classes in my inheritance tree would have telescoping constructors.
I have browsed for an answer here when I hit some problems during my design. First of, let me give you a simple, shallow example to illustrate the problem.
public class Rabbit
{
public String sex;
public String name;
public Rabbit(Builder builder)
{
sex = builder.sex;
name = builder.name;
}
public static class Builder
{
protected String sex;
protected String name;
public Builder() { }
public Builder sex(String sex)
{
this.sex = sex;
return this;
}
public Builder name(String name)
{
this.name = name;
return this;
}
public Rabbit build()
{
return new Rabbit(this);
}
}
}
public class Lop extends Rabbit
{
public float earLength;
public String furColour;
public Lop(LopBuilder builder)
{
super(builder);
this.earLength = builder.earLength;
this.furColour = builder.furColour;
}
public static class LopBuilder extends Rabbit.Builder
{
protected float earLength;
protected String furColour;
public LopBuilder() { }
public Builder earLength(float length)
{
this.earLength = length;
return this;
}
public Builder furColour(String colour)
{
this.furColour = colour;
return this;
}
public Lop build()
{
return new Lop(this);
}
}
}
Now that we have some code to go on, imaging I want to build a Lop:
Lop lop = new Lop.LopBuilder().furColour("Gray").name("Rabbit").earLength(4.6f);
This call will not compile as the last chained call cannot be resolved, Builder not defining the method earLength. So this way requires that all calls be chained in a specific order which is very impractical, especially with a deep hierarchy tree.
Now, during my search for an answer, I came across Subclassing a Java Builder class which suggests using the Curiously Recursive Generic Pattern. However, as my hierarchy does not contain an abstract class, this solution will not work for me. But the approach relies on abstraction and polymorphism to function which is why I don't believe I can adapt it to my needs.
An approach I have currently settled with is to override all methods of the superclass Builder in the hierarchy and simply do the following:
public ConcreteBuilder someOverridenMethod(Object someParameter)
{
super(someParameter);
return this;
}
With this approach I can assure I am being returned an instance I can issue chain calls on. While this is not as worse as the Telescoping Anti-pattern, it is a close second and I consider it a bit "hacky".
Is there another solution to my problem that I am not aware of? Preferably a solution consistent with the design pattern. Thank you!
This is certainly possible with the recursive bound, but the subtype builders need to also be generic, and you need a few interim abstract classes. It's a little bit cumbersome, but it's still easier than the non-generic version.
/**
* Extend this for Mammal subtype builders.
*/
abstract class GenericMammalBuilder<B extends GenericMammalBuilder<B>> {
String sex;
String name;
B sex(String sex) {
this.sex = sex;
return self();
}
B name(String name) {
this.name = name;
return self();
}
abstract Mammal build();
#SuppressWarnings("unchecked")
final B self() {
return (B) this;
}
}
/**
* Use this to actually build new Mammal instances.
*/
final class MammalBuilder extends GenericMammalBuilder<MammalBuilder> {
#Override
Mammal build() {
return new Mammal(this);
}
}
/**
* Extend this for Rabbit subtype builders, e.g. LopBuilder.
*/
abstract class GenericRabbitBuilder<B extends GenericRabbitBuilder<B>>
extends GenericMammalBuilder<B> {
Color furColor;
B furColor(Color furColor) {
this.furColor = furColor;
return self();
}
#Override
abstract Rabbit build();
}
/**
* Use this to actually build new Rabbit instances.
*/
final class RabbitBuilder extends GenericRabbitBuilder<RabbitBuilder> {
#Override
Rabbit build() {
return new Rabbit(this);
}
}
There's a way to avoid having the "concrete" leaf classes, where if we had this:
class MammalBuilder<B extends MammalBuilder<B>> {
...
}
class RabbitBuilder<B extends RabbitBuilder<B>>
extends MammalBuilder<B> {
...
}
Then you need to create new instances with a diamond, and use wildcards in the reference type:
static RabbitBuilder<?> builder() {
return new RabbitBuilder<>();
}
That works because the bound on the type variable ensures that all the methods of e.g. RabbitBuilder have a return type with RabbitBuilder, even when the type argument is just a wildcard.
I'm not much of a fan of that, though, because you need to use wildcards everywhere, and you can only create a new instance using the diamond or a raw type. I suppose you end up with a little awkwardness either way.
And by the way, about this:
#SuppressWarnings("unchecked")
final B self() {
return (B) this;
}
There's a way to avoid that unchecked cast, which is to make the method abstract:
abstract B self();
And then override it in the leaf subclass:
#Override
RabbitBuilder self() { return this; }
The issue with doing it that way is that although it's more type-safe, the subclass can return something other than this. Basically, either way, the subclass has the opportunity to do something wrong, so I don't really see much of a reason to prefer one of those approaches over the other.
Confronted with the same issue, I used the solution proposed by emcmanus at: https://community.oracle.com/blogs/emcmanus/2010/10/24/using-builder-pattern-subclasses
I'm just recopying his/her preferred solution here. Let say we have two classes, Shape and Rectangle. Rectangle inherits from Shape.
public class Shape {
private final double opacity;
public double getOpacity() {
return opacity;
}
protected static abstract class Init<T extends Init<T>> {
private double opacity;
protected abstract T self();
public T opacity(double opacity) {
this.opacity = opacity;
return self();
}
public Shape build() {
return new Shape(this);
}
}
public static class Builder extends Init<Builder> {
#Override
protected Builder self() {
return this;
}
}
protected Shape(Init<?> init) {
this.opacity = init.opacity;
}
}
There is the Init inner class, which is abstract, and the Builder inner class, that is an actual implementation. Will be useful when implementing the Rectangle:
public class Rectangle extends Shape {
private final double height;
public double getHeight() {
return height;
}
protected static abstract class Init<T extends Init<T>> extends Shape.Init<T> {
private double height;
public T height(double height) {
this.height = height;
return self();
}
public Rectangle build() {
return new Rectangle(this);
}
}
public static class Builder extends Init<Builder> {
#Override
protected Builder self() {
return this;
}
}
protected Rectangle(Init<?> init) {
super(init);
this.height = init.height;
}
}
To instantiate the Rectangle:
new Rectangle.Builder().opacity(1.0D).height(1.0D).build();
Again, an abstract Init class, inheriting from Shape.Init, and a Build that is the actual implementation. Each Builder class implement the self method, which is responsible to return a correctly cast version of itself.
Shape.Init <-- Shape.Builder
^
|
|
Rectangle.Init <-- Rectangle.Builder
If anyone still bumped into the same problem, I suggest the following solution, that conforms "Prefer composition over inheritance" design pattern.
Parent class
The main element of it is the interface that parent class Builder must implement:
public interface RabbitBuilder<T> {
public T sex(String sex);
public T name(String name);
}
Here is the changed parent class with the change:
public class Rabbit {
public String sex;
public String name;
public Rabbit(Builder builder) {
sex = builder.sex;
name = builder.name;
}
public static class Builder implements RabbitBuilder<Builder> {
protected String sex;
protected String name;
public Builder() {}
public Rabbit build() {
return new Rabbit(this);
}
#Override
public Builder sex(String sex) {
this.sex = sex;
return this;
}
#Override
public Builder name(String name) {
this.name = name;
return this;
}
}
}
The child class
The child class Builder must implement the same interface (with different generic type):
public static class LopBuilder implements RabbitBuilder<LopBuilder>
Inside the child class Builder the field referencing parentBuilder:
private Rabbit.Builder baseBuilder;
this ensures that parent Builder methods are called in the child, however, their implementation is different:
#Override
public LopBuilder sex(String sex) {
baseBuilder.sex(sex);
return this;
}
#Override
public LopBuilder name(String name) {
baseBuilder.name(name);
return this;
}
public Rabbit build() {
return new Lop(this);
}
The constructor of Builder:
public LopBuilder() {
baseBuilder = new Rabbit.Builder();
}
The constructor of builded child class:
public Lop(LopBuilder builder) {
super(builder.baseBuilder);
}
I have adopted the following guidelines when creating object hierarchies with builders:
Make the constructor of the class at least protected and use it as copy constructor, thus pass it an instance of the class itself.
Make the fields non-final private and use getters to access them.
Add package private setters for the builders, which is also nice for object serialization frameworks.
Make a generic builder for each class that will have a subclass builder. This builder will already contain the setter methods for the current class, but we create also a second non generic builder for the class that contains the constructor and build method.
The builders will not have any fields. Instead the generic builder that is on top of the hierarchy will contain a generic field for the concrete object to be build.
The Rabbit will look like this:
public class Rabbit {
// private non-final fields
private String sex;
private String name;
// copy constructor
Rabbit(Rabbit rabbit) {
sex = rabbit.sex;
name = rabbit.name;
}
// no-arg constructor for serialization and builder
Rabbit() {}
// getter methods
public final String getSex() {
return sex;
}
public final String getName() {
return name;
}
// package private setter methods, good for serialization frameworks
final void setSex(String sex) {
this.sex = sex;
}
final void setName(String name) {
this.name = name;
}
// create a generic builder for builders that have subclass builders
abstract static class RBuilder<R extends Rabbit, B extends RBuilder<R, B>> {
// the builder creates the rabbit
final R rabbit;
// here we pass the concrete subclass that will be constructed
RBuilder(R rabbit) {
this.rabbit = rabbit;
}
public final B sex(String sex) {
rabbit.setSex(sex);
return self();
}
public final B name(String name) {
rabbit.setName(name);
return self();
}
#SuppressWarnings("unchecked")
final B self() {
return (B) this;
}
}
// the builder that creates the rabbits
public static final class Builder extends RBuilder<Rabbit, Builder> {
// creates a new rabbit builder
public Builder() {
super(new Rabbit());
}
// we could provide a public copy constructor to support modifying rabbits
public Builder(Rabbit rabbit) {
super(new Rabbit(rabbit));
}
// create the final rabbit
public Rabbit build() {
// maybe make a validate method call before?
return new Rabbit(rabbit);
}
}
}
and our Lop:
public final class Lop extends Rabbit {
// private non-final fields
private float earLength;
private String furColour;
// copy constructor
private Lop(Lop lop) {
super(lop);
this.earLength = lop.earLength;
this.furColour = lop.furColour;
}
// no-arg constructor for serialization and builder
Lop() {}
// getter methods
public final float getEarLength() {
return earLength;
}
public final String getFurColour() {
return furColour;
}
// package private setter methods, good for serialization frameworks
final void setEarLength(float earLength) {
this.earLength = earLength;
}
final void setFurColour(String furColour) {
this.furColour = furColour;
}
// the builder that creates lops
public static final class Builder extends RBuilder<Lop, Builder> {
public Builder() {
super(new Lop());
}
// we could provide a public copy constructor to support modifying lops
public Builder(Lop lop) {
super(new Lop(lop));
}
public final Builder earLength(float length) {
rabbit.setEarLength(length);
return self(); // this works also here
}
public final Builder furColour(String colour) {
rabbit.setFurColour(colour);
return self();
}
public Lop build() {
return new Lop(rabbit);
}
}
}
Pros:
The builders will exactly mirror the object hierarchy of your classes with a single derivative for each generic builder to build the objects of the current class. No need to create artificial parents.
The class does not have a dependency to its builder. All it needs is an instance of itself to copy the fields, which might be useful for alternative factories.
The classes work very well with serialization frameworks like JSON or Hibernate, since they most often need getters and setters to be present. E.g. Jackson works fine with package private setters.
No need to duplicate fields in the builder. The builder contains the object to be constructed.
No need to override setter methods in the subtype builders since the direct parent class is generic.
Build-in support for copy constructors to allow creating a modified version of an instance, making the objects 'kind of immutable'.
Cons:
Requires at least one additional generic builder.
Fields are not final, thus it's not safe to make them public.
The class itself needs additional setter methods to be called from the builders.
Let's create some rabbits..
#Test
void test() {
// creating a rabbit
Rabbit rabbit = new Rabbit.Builder() //
.sex("M")
.name("Rogger")
.build();
assertEquals("M", rabbit.getSex());
// create a lop
Lop lop = new Lop.Builder() //
.furColour("Gray")
.name("Rabbit")
.earLength(4.6f)
.build();
// modify only the name of the lop
lop = new Lop.Builder(lop) //
.name("Lop")
.build();
assertEquals("Gray", lop.getFurColour());
assertEquals("Lop", lop.getName());
}
This form seems to nearly work. It is not very tidy but it looks like it avoids your issues:
class Rabbit<B extends Rabbit.Builder<B>> {
String name;
public Rabbit(Builder<B> builder) {
this.name = builder.colour;
}
public static class Builder<B extends Rabbit.Builder<B>> {
protected String colour;
public B colour(String colour) {
this.colour = colour;
return (B)this;
}
public Rabbit<B> build () {
return new Rabbit<>(this);
}
}
}
class Lop<B extends Lop.Builder<B>> extends Rabbit<B> {
float earLength;
public Lop(Builder<B> builder) {
super(builder);
this.earLength = builder.earLength;
}
public static class Builder<B extends Lop.Builder<B>> extends Rabbit.Builder<B> {
protected float earLength;
public B earLength(float earLength) {
this.earLength = earLength;
return (B)this;
}
#Override
public Lop<B> build () {
return new Lop<>(this);
}
}
}
public class Test {
public void test() {
Rabbit rabbit = new Rabbit.Builder<>().colour("White").build();
Lop lop1 = new Lop.Builder<>().earLength(1.4F).colour("Brown").build();
Lop lop2 = new Lop.Builder<>().colour("Brown").earLength(1.4F).build();
//Lop.Builder<Lop, Lop.Builder> builder = new Lop.Builder<>();
}
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
}
Although I have successfully built Rabbit and Lop (in both forms) I cannot at this stage work out how to actually instantiate one of the Builder objects with it's full type.
The essence of this method relies on the cast to (B) in the Builder methods. This allow you to define the type of object and the type of the Builder and retain that within the object while it is constructed.
If anyone could work out the correct syntax for this (which is wrong) I would appreciate it.
Lop.Builder<Lop.Builder> builder = new Lop.Builder<>();
I did some experimenting and I found this to work quite nicely for me.
Note that I prefer to create the actual instance at the start and the call all the setters on that instance. This is just a preference.
The main differences with the accepted answer is that
I pass a parameter that indicated the return type
There is no need for an Abstract... and a final builder.
I create a 'newBuilder' convenience method.
The code:
public class MySuper {
private int superProperty;
public MySuper() { }
public void setSuperProperty(int superProperty) {
this.superProperty = superProperty;
}
public static SuperBuilder<? extends MySuper, ? extends SuperBuilder> newBuilder() {
return new SuperBuilder<>(new MySuper());
}
public static class SuperBuilder<R extends MySuper, B extends SuperBuilder<R, B>> {
private final R mySuper;
public SuperBuilder(R mySuper) {
this.mySuper = mySuper;
}
public B withSuper(int value) {
mySuper.setSuperProperty(value);
return (B) this;
}
public R build() {
return mySuper;
}
}
}
and then a subclass look like this:
public class MySub extends MySuper {
int subProperty;
public MySub() {
}
public void setSubProperty(int subProperty) {
this.subProperty = subProperty;
}
public static SubBuilder<? extends MySub, ? extends SubBuilder> newBuilder() {
return new SubBuilder(new MySub());
}
public static class SubBuilder<R extends MySub, B extends SubBuilder<R, B>>
extends SuperBuilder<R, B> {
private final R mySub;
public SubBuilder(R mySub) {
super(mySub);
this.mySub = mySub;
}
public B withSub(int value) {
mySub.setSubProperty(value);
return (B) this;
}
}
}
and a subsub class
public class MySubSub extends MySub {
private int subSubProperty;
public MySubSub() {
}
public void setSubSubProperty(int subProperty) {
this.subSubProperty = subProperty;
}
public static SubSubBuilder<? extends MySubSub, ? extends SubSubBuilder> newBuilder() {
return new SubSubBuilder<>(new MySubSub());
}
public static class SubSubBuilder<R extends MySubSub, B extends SubSubBuilder<R, B>>
extends SubBuilder<R, B> {
private final R mySubSub;
public SubSubBuilder(R mySub) {
super(mySub);
this.mySubSub = mySub;
}
public B withSubSub(int value) {
mySubSub.setSubSubProperty(value);
return (B)this;
}
}
}
To verify it fully works I used this test:
MySubSub subSub = MySubSub
.newBuilder()
.withSuper (1)
.withSub (2)
.withSubSub(3)
.withSub (2)
.withSuper (1)
.withSubSub(3)
.withSuper (1)
.withSub (2)
.build();
The following IEEE conference contribution Refined Fluent Builder in Java gives a comprehensive solution to the problem.
It dissects the original question into two sub-problems of inheritance deficiency and quasi invariance and shows how a solution to these two sub-problems opens for inheritance support with code reuse in the classical builder pattern in Java.
As you cannot use generics, now probably the main task is to somehow loosen typing.
I don't know how you process those properties afterwards, but what if you used a HashMap for storing them as key-value pairs? So there will be just one set(key, value) wrapper method in the builder (or builder might not be necessary any more).
The downside would be additional type castings while processing the stored data.
If this case is too loose, then you could keep the existing properties, but have a general set method, which uses reflection and searches for setter method on the basis of 'key' name. Although I think reflection would be an overkill.
I want to enforce enum implementation in Java but I found out that I couldn't do it.
So I decided to define an abstract function that returns the enums of subclasses. But don't know how to do it.
Here is the code:
EnumInterface
public interface EnumInterface
{
public String getString();
}
ParentClass
public abstract class ParentClass {
public abstract Enum<?> getEnums();
}
ChildClass
public class ChildClass extends ParentClass{
public enum EnumImplementation implements EnumInterface
{
FOO("foo"),
BAR("bar");
String string;
EnumImplementation(String field)
{
this.string = string;
}
#Override
public String getString() {
return string;
}
}
#Override
public Enum<?> getEnums() {
return ?;
}
}
The code above doesn't work, I'm just trying to describe my problem.
I also want to enforce the enum return type to EnumInterface if possible.
If you know how to enforce specific enum implementation that would be better as I don't even have to define the function in ParentClass.
So, how do I return the enum so that I can just do this instanceOfParentClass.getEnums().FOO?
What about this:
public <T extends Enum<T> & EnumInterface> T[] getEnums() {
return (T[])EnumImplementation.values();
}
Note the cast, which might result in a ClassCastException.
To prevent this you could pass the enum class or just return an array of EnumInterface:
public <T extends Enum<T> & EnumInterface> T[] getEnums(Class<T> enumType)
public <T extends Enum<T> & EnumInterface> EnumInterface[] getEnums()
Note that this doesn't enable you to call the method like getEnums().FOO, but you could pass the class and the name, e.g.
public <T extends Enum<T> & EnumInterface> T[] getEnum(Class<T> enumType, String enumName) {
return Enum.valueOf( enumType, enumName);
}
However, just as Tim B said, there might be a better option for what you're trying to achieve.
Try this.
EnumInterface
public interface EnumInterface {
public String getString();
}
ParentClass
public abstract class ParentClass<ENUM_TYPE extends Enum<ENUM_TYPE> & EnumInterface> {
public abstract ENUM_TYPE getEnums();
}
ChildClass
public class ChildClass extends ParentClass<ChildClass.EnumImplementation> {
public static enum EnumImplementation implements EnumInterface {
FOO("foo"),
BAR("bar");
String string;
EnumImplementation(String field) {
this.string = field;
}
#Override
public String getString() {
return string;
}
}
public EnumImplementation getEnums() {
return EnumImplementation.values()[0];
}
public static void test() {
Object result = new ChildClass().getEnums().FOO;
}
}
Note that getEnums() returns an enum value. It's not possible to return the enum container itself, but you can call other enum values from any value (f.e. EnumImplementation.FOO.BAR.FOO)
In order to map property names to database field you can use the enum valueOf method.
You need to do the mapping in your class as you cannot pass a reference to the static enumeration:
http://www.tryjava8.com/app/snippets/52b86150e4b0f5090255bc45
import java.util.*;
public class Main{
static enum TestE {
FOO,
BAR
}
static class TestC {
TestE getEnum(String name) {
return TestE.valueOf(name);
}
}
public static void main(String[] args){
System.out.println(TestE.FOO);
System.out.println(new TestC().getEnum("BAR"));
}
}
I am trying to design a factory for a pluggable interface. The idea is that once you have your factory instance, the factory will return the appropriate subclasses for that particular implementation.
In this case, I am wrapping a third party library that uses a String to represent an ID code, rather than subclasses. Therefore, in the implementation that wraps their library, every implementation class has a method getCode() that is not explicitly required by the interface API. I am using an enum to store this mapping between codes and interface classes.
In nearly all cases, the getCode() method is not needed. However, in just a few situations in the implementation package, I need access to that method. Therefore, my problem is that I would like to have the Factory implementation's signature tell callers that the getCode method exists if they have a reference to the specific Factory implementation.
What follows is a lot of code in my best-effort attempt to digest the situation into an sscce. I know it's very long, but it's simpler than it seems, and one of the words in sscce is "complete".
Public API:
public interface Factory {
public <T extends IFoo> T makeIFoo(Class<T> klass);
}
public interface IFoo {
void doSomething();
}
public interface IFooBar extends IFoo {
void doBarTask();
}
public interface IFooBaz extends IFoo {
void doBazTask();
}
Sample use case:
public class SomeClass {
private Factory myFactory;
public void doSomething() {
IFooBar ifb = myFactory.create(IFooBar.class);
}
}
SSCCE version of implementation:
interface ICode {
String getCode();
}
abstract class BaseCode implements IFoo, ICode {
private String code;
BaseCode(String code) {
this.code = code;
}
#Override
public String getCode() {
return code;
}
#Override
public void doSomething() {
System.out.println("Something");
}
}
class FooBarImpl extends BaseCode implements ICode, IFooBar {
FooBarImpl(String code) {
super(code);
}
#Override
public void doBarTask() {
System.out.println("BarTask");
}
}
class FooBazImpl extends BaseCode implements ICode, IFooBaz {
FooBazImpl(String code) {
super(code);
}
#Override
public void doBazTask() {
System.out.println("BarTask");
}
}
Enum codemapper:
static enum CodeMap {
FOOBAR ("A", IFooBar.class) {
FooBarImpl create() { return new FooBarImpl(getCode()); }
},
FOOBAZ ("B", IFooBaz.class) {
FooBazImpl create() { return new FooBazImpl(getCode()); }
};
private static Map<Class<? extends IFoo>, CodeMap> classMap;
static {
classMap = new HashMap<Class<? extends IFoo>, CodeMap>();
for(CodeMap cm : CodeMap.values()) {
classMap.put(cm.getFooClass(), cm);
}
}
private String code;
private Class<? extends IFoo> klass;
private CodeMap(String code, Class<? extends IFoo> klass) {
this.code = code;
this.klass = klass;
}
String getCode() {
return code;
}
Class<? extends IFoo> getFooClass() {
return klass;
}
static CodeMap getFromClass(Class<? extends IFoo> klass) {
return classMap.get(klass);
}
abstract BaseCode create();
}
Sample use case within implementation package:
public class InternalClass {
CodeFactory factory;
public void doSomething() {
FooBarImpl fb = factory.makeIFoo(IFooBar.class);
}
}
Attempt at factory:
This does not specify that the return will always implement ICode. But the passed-in interface class DOESN'T implement ICode, that's the whole point.
class CodeFactory implements Factory {
#Override
public <T extends IFoo> T makeIFoo(Class<T> klass) {
CodeMap map = CodeMap.getFromClass(klass);
if (map == null) return null; // Or throw an exception, whatever, SSCCE
return (T) map.create();
}
}
What should I do?
I realized I was making this too complicated. If I'm going to implement a factory method for each enum instance, I may as well just have separate factory methods for each interface.
public interface Factory {
IFooBar createFooBar();
IFooBaz createFooBaz();
}
class CodeFactory implements Factory {
public FooBarImpl createFooBar() {
// etc.
}
}
Of course now I have to change the Factory API if there are ever new interfaces, but I expect that will be rare.
A possible solution would be defining a wrapper that implements IFoo and the getCode() method, and your method would return the intended class in one of such wrappers.
If the wrapped instance has a getCode implemented, the wrapper would return its value, return it, otherwise return null.