Java Enum one to one to another Enum [duplicate] - java

Is there a way to get around the class-loading issues caused by having two enums that reference each other?
I have two sets of enumerations, Foo and Bar, defined like so:
public class EnumTest {
public enum Foo {
A(Bar.Alpha),
B(Bar.Delta),
C(Bar.Alpha);
private Foo(Bar b) {
this.b = b;
}
public final Bar b;
}
public enum Bar {
Alpha(Foo.A),
Beta(Foo.C),
Delta(Foo.C);
private Bar(Foo f) {
this.f = f;
}
public final Foo f;
}
public static void main (String[] args) {
for (Foo f: Foo.values()) {
System.out.println(f + " bar " + f.b);
}
for (Bar b: Bar.values()) {
System.out.println(b + " foo " + b.f);
}
}
}
The above code produces as output:
A bar Alpha
B bar Delta
C bar Alpha
Alpha foo null
Beta foo null
Delta foo null
I understand why it happens - the JVM starts classloading Foo; it sees the Bar.Alpha in Foo.A's constructor, so it starts classloading Bar. It sees the Foo.A reference in the call to Bar.Alpha's constructor, but (since we're still in Foo.A's constructor) Foo.A is null at this point, so Bar.Alpha's constructor gets passed a null. If I reverse the two for loops (or otherwise reference Bar before Foo), the output changes so that Bar's values are all correct, but Foo's values are not.
Is there any way to get around this? I know I can create a static Map and a static Map in a 3rd class, but that feels fairly hackish to me. I could also make Foo.getBar() and Bar.getFoo() methods that refer to the external map, so it wouldn't even change my interface (the actual classes I have use inspectors instead of public fields), but it still feels kind of unclean to me.
(The reason I'm doing this in my actual system: Foo and Bar represent types of messages that 2 apps send to each other; the Foo.b and Bar.f fields represent the expected response type for a given message - so in my sample code, when app_1 receives a Foo.A, it needs to reply with a Bar.Alpha and vice-versa.)
Thanks in advance!

One of the best ways would be using the enum polymorphism technique:
public class EnumTest {
public enum Foo {
A {
#Override
public Bar getBar() {
return Bar.Alpha;
}
},
B {
#Override
public Bar getBar() {
return Bar.Delta;
}
},
C {
#Override
public Bar getBar() {
return Bar.Alpha;
}
},
;
public abstract Bar getBar();
}
public enum Bar {
Alpha {
#Override
public Foo getFoo() {
return Foo.A;
}
},
Beta {
#Override
public Foo getFoo() {
return Foo.C;
}
},
Delta {
#Override
public Foo getFoo() {
return Foo.C;
}
},
;
public abstract Foo getFoo();
}
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.println(f + " bar " + f.getBar());
}
for (Bar b : Bar.values()) {
System.out.println(b + " foo " + b.getFoo());
}
}
}
The above code produces the output you want:
A bar Alpha
B bar Delta
C bar Alpha
Alpha foo A
Beta foo C
Delta foo C
See also:
Overridding method of a specific enum

The issue isn't so much "two enums reference each other", it's more "two enums reference each other in their constructors". This circular reference is the tricky part.
How about using Foo.setResponse(Bar b) and Bar.setResponse(Foo f) methods? Instead of setting a Foo's Bar in the Foo constructor (and similarly a Bar's Foo in the Bar constructor), you do the initialization using a method? E.g.:
Foo:
public enum Foo {
A, B, C;
private void setResponse(Bar b) {
this.b = b;
}
private Bar b;
public Bar getB() {
return b;
}
static {
A.setResponse(Bar.Alpha);
B.setResponse(Bar.Delta);
C.setResponse(Bar.Alpha);
}
}
Bar:
public enum Bar {
Alpha, Beta, Delta;
private void setResponse(Foo f) {
this.f = f;
}
private Foo f;
public Foo getF() {
return f;
}
static {
Alpha.setResponse(Foo.A);
Beta.setResponse(Foo.C);
Delta.setResponse(Foo.C);
}
}
Also, you mention that Foo and Bar are two types of messages. Would it be possible to combine them into a single type? From what I can see, their behavior here is the same. This doesn't fix the circular logic, but it might give you some other insight into your design...

Since it seems you're going to be hard-coding anyways, why not have something like
public static Bar responseBar(Foo f) {
switch(f) {
case A: return Bar.Alpha;
// ... etc
}
}
for each enum? It looks like you have some overlapping responses in your example, so you could even take advantage of cases falling through.
EDIT:
I like Tom's suggestion of the EnumMap; I think performance is probably faster on the EnumMap, but the sort of elegant construction described in Effective Java doesn't seem to be afforded by this particular problem - however, the switch solution offered above would be a good way to construct two static EnumMaps, then the response could be something like:
public static Bar response(Foo f) { return FooToBar.get(f); }
public static Foo response(Bar b) { return BarToFoo.get(b); }

Interesting design. I see your need, but what are you going to do when the requirements shift slightly, so that in response to Foo.Epsilon, app_1 should send either a Bar.Gamma or a Bar.Whatsit?
The solution you considered and discarded as hackish (putting the relation into a map) seems to give you much more flexibility, and avoids your circular reference. It also keeps the responsibility partitioned: the message types themselves shouldn't be responsible for knowing their response, should they?

You can use EnumMap, and fill it within one of the enums.
private static EnumMap<Foo, LinkedList<Bar>> enumAMap;
public static void main(String[] args) throws Exception {
enumAMap = new EnumMap<Foo, LinkedList<Bar>>(Foo.class);
System.out.println(Bar.values().length); // initialize enums, prevents NPE
for (Foo a : Foo.values()) {
for (Bar b : enumAMap.get(a)) {
System.out.println(a + " -> " + b);
}
}
}
public enum Foo {
Foo1(1),
Foo2(2);
private int num;
private Foo(int num) {
this.num = num;
}
public int getNum() {
return num;
}
}
public enum Bar {
Bar1(1, Foo.Foo1),
Bar2(2, Foo.Foo1),
Bar3(3, Foo.Foo2),
Bar4(4, Foo.Foo2);
private int num;
private Foo foo;
private Bar(int num, Foo foo) {
this.num = num;
this.foo = foo;
if (!enumAMap.containsKey(foo)) {
enumAMap.put(foo, new LinkedList<Bar>());
}
enumAMap.get(foo).addLast(this);
}
public int getNum() {
return num;
}
public Foo getFoo() {
return foo;
}
}
Output:
4
Foo1 -> Bar1
Foo1 -> Bar2
Foo2 -> Bar3
Foo2 -> Bar4

Here is an updated version of #falsarella's answer. This uses Java 8 Lambdas and java.util.function, however the principal is the same. It's just a little more succinct with the newer syntax:
import java.util.function.Supplier;
public class EnumTest {
public enum Foo {
A(() -> Bar.Alpha), B(() -> Bar.Beta), C(() -> Bar.Delta);
private final Supplier<Bar> bar;
private Foo(Supplier<Bar> bar) {
this.bar = bar;
}
public Bar getBar() {
return bar.get();
}
}
public enum Bar {
Alpha(() -> Foo.A), Beta(() -> Foo.B), Delta(() -> Foo.C);
private final Supplier<Foo> foo;
private Bar(Supplier<Foo> foo) {
this.foo = foo;
}
public Foo getFoo() {
return foo.get();
}
}
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.println(f + " bar " + f.getBar());
}
for (Bar b : Bar.values()) {
System.out.println(b + " foo " + b.getFoo());
}
}
}

Related

How to extend a class that is returning this in their methods

The question is easy but I'm not sure it's possible to do it...
if we have a class like
class A {
private int foo;
public A(int bar) {
this.foo = bar;
}
public A setFoo(int bar) {
this.foo = bar;
return this;
}
public int getFoo() {
return this.foo;
}
public void doSomething() {
this.foo++;
}
}
we can see that it's just simply a class with a private member and a setter/getter.
The interesting thing is, to allow method chaining, the setter is returning this.
So we can do things like this:
A a = new A(0);
a.setFoo(1).doSomething();
The problem here is when I try to extend that class add some functionality implementing an interface like this
class B extends A implements I {
public B(int bar) {
this.super(bar);
}
public void methodI() {
// whatever
}
}
It seems ok, until I start using it like this
B b = new B(1);
b.setFoo(2).methodI();
Because setFoo is actually returning an instance of A, not an instance of B, and in A methodI doesn't exist...
Any workaround? Thanks.
By the way, I just wrote a basic code simply to understand, but if you want to know more, I'm just trying to extend the some of the basic classes of libgdx (like Math.Vector2, Math.Vector3) to implement Poolable.
Class B can override the method setFoo and change the return type to B because B is a more specific version of A. An overridden method can have a more specific return type. e.g.
class B extends A implements I {
public B(int bar) {
this.super(bar);
}
public void methodI() {
// whatever
}
#Override
public B setFoo(int bar) {
this.foo = bar;
return this;
}
}
You should use generics here:
public class A<T extends A<?>> {
public T self() {
return (T) this;
}
private int foo;
public A(int bar) {
this.foo = bar;
}
public T setFoo(int bar) {
this.foo = bar;
return self();
}
public int getFoo() {
return this.foo;
}
public void doSomething() {
this.foo++;
}
}
public class B<T extends B<?>> extends A<T> implements I {
public B(int bar) {
this.super(bar);
}
public void methodI() {
// whatever
}
}
Now you will be able to use such chained calls:
B b = new B(1);
b.setFoo(2).methodI();
Have run into this before as well. Don't think there's a baked in simple solution. Consider overriding all setter methods:
class B extends A implements I {
#Override
public A setFoo(int bar) {
super.setFoo(bar);
return this;
}
}
For completeness (i.e. I do not consider this a better solution than the above, just may be appropriate) and certainly not an answer to the title of your question but a possible solution to your problem.
You could consider using default methods offered by Java 8. It is specifically for adding functionality to existing classes.
// From LibGDX Pool.Poolable
interface Poolable {
public void reset();
}
// Class A untouched.
class A {
private int foo;
public A(int bar) {
this.foo = bar;
}
public A setFoo(int bar) {
this.foo = bar;
return this;
}
public int getFoo() {
return this.foo;
}
public void doSomething() {
this.foo++;
}
}
// Extend Poolable to add the functionality.
interface PoolableVector extends Poolable {
default void reset() {
// Not sure what you want to do here.
}
}
// A Poolable A trivially made.
class B extends A implements PoolableVector {
public B(int b) {
super(b);
}
}
Just have setFoo() return void, and then you can do:
B b = new B(1);
b.setFoo(2);
b.methodI();

Output of Java program

I am a Java beginner.
Can anyone explain why is it printing output 2?
interface Foo {
int bar();
}
public class Beta {
class A implements Foo {
public int bar() {
return 1;
}
}
public int fubar(final Foo foo) {
return foo.bar();
}
public void testFoo()// 2
{
class A implements Foo {
public int bar() {
return 2;
}
}
System.out.println(fubar(new A()));
}
public static void main(String[] args) {
new Beta().testFoo();
}
}
That is because you redefined Class A here:
class A implements Foo {
public int bar() {
return 2;
}
}
System.out.println(fubar(new A()));
So when you do return foo.bar(); you return 2
Because the innermost definition of A is in the testFoo() method, and its method bar() return 2.
You may also find the answer to my question from today interesting.
When you say, System.out.println(fubar(new A()));
the class A created is the one defined inside testFoo().
There are many places in java where you can hide a broader name with a more local name. This is true of parameters vs member variables, class names etc. In your case, you are hiding Beta.A with the A you defined in the method.

Options/enums in java?

Is there a best practice for enumerations in java? For example, I have the following:
class Foo {
public static final int OPTION_1 = 'a';
public static final int OPTION_2 = 'b';
public void doSomething(String name, int option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.doSomething("blah", Foo.OPTION_2);
}
so the user can choose to use one of the static ints defined in Foo, but they could also supply any other int they want, there's no compile-time checking on it. Is there some way around this in java, some other way of doing this to restrict the end developer to choose from only the defined option types?
Thanks
class Foo {
public enum Option{First, Second}
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Foo.Option.Second);
}
Since Java 1.5 there is the enum keyword which makes typesafe enumerations
Your code would look like this then :
class Foo {
public enum Option = { OPTION_1, OPTION_2 };
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.doSomething("blah", Foo.Option.OPTION_2);
}
This is fully supported by the type system so the compiler will enforce the user not to become to creative when passing options.
You can read more here
There are enum types in Java (as of J2SE 5.0). Read the tutorial.
public enum Option{
OPTION_1, OPTION_2 //All caps by convention
}
class Foo {
public void dosomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Option.OPTION_2);
}
you even can add method into enum, check it out at sun document http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
This will allow you to set the value of the enum
enum Option{
ONE('a');
TWO('b');
private Option(int x){
value = x;
}
private int value;
}
class Foo {
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Option.ONE);
}

Java Enums: Two enum types, each containing references to each other?

Is there a way to get around the class-loading issues caused by having two enums that reference each other?
I have two sets of enumerations, Foo and Bar, defined like so:
public class EnumTest {
public enum Foo {
A(Bar.Alpha),
B(Bar.Delta),
C(Bar.Alpha);
private Foo(Bar b) {
this.b = b;
}
public final Bar b;
}
public enum Bar {
Alpha(Foo.A),
Beta(Foo.C),
Delta(Foo.C);
private Bar(Foo f) {
this.f = f;
}
public final Foo f;
}
public static void main (String[] args) {
for (Foo f: Foo.values()) {
System.out.println(f + " bar " + f.b);
}
for (Bar b: Bar.values()) {
System.out.println(b + " foo " + b.f);
}
}
}
The above code produces as output:
A bar Alpha
B bar Delta
C bar Alpha
Alpha foo null
Beta foo null
Delta foo null
I understand why it happens - the JVM starts classloading Foo; it sees the Bar.Alpha in Foo.A's constructor, so it starts classloading Bar. It sees the Foo.A reference in the call to Bar.Alpha's constructor, but (since we're still in Foo.A's constructor) Foo.A is null at this point, so Bar.Alpha's constructor gets passed a null. If I reverse the two for loops (or otherwise reference Bar before Foo), the output changes so that Bar's values are all correct, but Foo's values are not.
Is there any way to get around this? I know I can create a static Map and a static Map in a 3rd class, but that feels fairly hackish to me. I could also make Foo.getBar() and Bar.getFoo() methods that refer to the external map, so it wouldn't even change my interface (the actual classes I have use inspectors instead of public fields), but it still feels kind of unclean to me.
(The reason I'm doing this in my actual system: Foo and Bar represent types of messages that 2 apps send to each other; the Foo.b and Bar.f fields represent the expected response type for a given message - so in my sample code, when app_1 receives a Foo.A, it needs to reply with a Bar.Alpha and vice-versa.)
Thanks in advance!
One of the best ways would be using the enum polymorphism technique:
public class EnumTest {
public enum Foo {
A {
#Override
public Bar getBar() {
return Bar.Alpha;
}
},
B {
#Override
public Bar getBar() {
return Bar.Delta;
}
},
C {
#Override
public Bar getBar() {
return Bar.Alpha;
}
},
;
public abstract Bar getBar();
}
public enum Bar {
Alpha {
#Override
public Foo getFoo() {
return Foo.A;
}
},
Beta {
#Override
public Foo getFoo() {
return Foo.C;
}
},
Delta {
#Override
public Foo getFoo() {
return Foo.C;
}
},
;
public abstract Foo getFoo();
}
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.println(f + " bar " + f.getBar());
}
for (Bar b : Bar.values()) {
System.out.println(b + " foo " + b.getFoo());
}
}
}
The above code produces the output you want:
A bar Alpha
B bar Delta
C bar Alpha
Alpha foo A
Beta foo C
Delta foo C
See also:
Overridding method of a specific enum
The issue isn't so much "two enums reference each other", it's more "two enums reference each other in their constructors". This circular reference is the tricky part.
How about using Foo.setResponse(Bar b) and Bar.setResponse(Foo f) methods? Instead of setting a Foo's Bar in the Foo constructor (and similarly a Bar's Foo in the Bar constructor), you do the initialization using a method? E.g.:
Foo:
public enum Foo {
A, B, C;
private void setResponse(Bar b) {
this.b = b;
}
private Bar b;
public Bar getB() {
return b;
}
static {
A.setResponse(Bar.Alpha);
B.setResponse(Bar.Delta);
C.setResponse(Bar.Alpha);
}
}
Bar:
public enum Bar {
Alpha, Beta, Delta;
private void setResponse(Foo f) {
this.f = f;
}
private Foo f;
public Foo getF() {
return f;
}
static {
Alpha.setResponse(Foo.A);
Beta.setResponse(Foo.C);
Delta.setResponse(Foo.C);
}
}
Also, you mention that Foo and Bar are two types of messages. Would it be possible to combine them into a single type? From what I can see, their behavior here is the same. This doesn't fix the circular logic, but it might give you some other insight into your design...
Since it seems you're going to be hard-coding anyways, why not have something like
public static Bar responseBar(Foo f) {
switch(f) {
case A: return Bar.Alpha;
// ... etc
}
}
for each enum? It looks like you have some overlapping responses in your example, so you could even take advantage of cases falling through.
EDIT:
I like Tom's suggestion of the EnumMap; I think performance is probably faster on the EnumMap, but the sort of elegant construction described in Effective Java doesn't seem to be afforded by this particular problem - however, the switch solution offered above would be a good way to construct two static EnumMaps, then the response could be something like:
public static Bar response(Foo f) { return FooToBar.get(f); }
public static Foo response(Bar b) { return BarToFoo.get(b); }
Interesting design. I see your need, but what are you going to do when the requirements shift slightly, so that in response to Foo.Epsilon, app_1 should send either a Bar.Gamma or a Bar.Whatsit?
The solution you considered and discarded as hackish (putting the relation into a map) seems to give you much more flexibility, and avoids your circular reference. It also keeps the responsibility partitioned: the message types themselves shouldn't be responsible for knowing their response, should they?
You can use EnumMap, and fill it within one of the enums.
private static EnumMap<Foo, LinkedList<Bar>> enumAMap;
public static void main(String[] args) throws Exception {
enumAMap = new EnumMap<Foo, LinkedList<Bar>>(Foo.class);
System.out.println(Bar.values().length); // initialize enums, prevents NPE
for (Foo a : Foo.values()) {
for (Bar b : enumAMap.get(a)) {
System.out.println(a + " -> " + b);
}
}
}
public enum Foo {
Foo1(1),
Foo2(2);
private int num;
private Foo(int num) {
this.num = num;
}
public int getNum() {
return num;
}
}
public enum Bar {
Bar1(1, Foo.Foo1),
Bar2(2, Foo.Foo1),
Bar3(3, Foo.Foo2),
Bar4(4, Foo.Foo2);
private int num;
private Foo foo;
private Bar(int num, Foo foo) {
this.num = num;
this.foo = foo;
if (!enumAMap.containsKey(foo)) {
enumAMap.put(foo, new LinkedList<Bar>());
}
enumAMap.get(foo).addLast(this);
}
public int getNum() {
return num;
}
public Foo getFoo() {
return foo;
}
}
Output:
4
Foo1 -> Bar1
Foo1 -> Bar2
Foo2 -> Bar3
Foo2 -> Bar4
Here is an updated version of #falsarella's answer. This uses Java 8 Lambdas and java.util.function, however the principal is the same. It's just a little more succinct with the newer syntax:
import java.util.function.Supplier;
public class EnumTest {
public enum Foo {
A(() -> Bar.Alpha), B(() -> Bar.Beta), C(() -> Bar.Delta);
private final Supplier<Bar> bar;
private Foo(Supplier<Bar> bar) {
this.bar = bar;
}
public Bar getBar() {
return bar.get();
}
}
public enum Bar {
Alpha(() -> Foo.A), Beta(() -> Foo.B), Delta(() -> Foo.C);
private final Supplier<Foo> foo;
private Bar(Supplier<Foo> foo) {
this.foo = foo;
}
public Foo getFoo() {
return foo.get();
}
}
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.println(f + " bar " + f.getBar());
}
for (Bar b : Bar.values()) {
System.out.println(b + " foo " + b.getFoo());
}
}
}

How to refer to the outer class in another instance of a non-static inner class?

I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:
import org.apache.commons.lang.builder.EqualsBuilder;
public class Foo {
public class Bar {
private Bar() {}
public Foo getMyFoo() {
return Foo.this
}
private int myInt = 0;
public boolean equals(Object o) {
if (o == null || o.getClass() != getClass) return false;
Bar other = (Bar) o;
return new EqualsBuilder()
.append(getMyFoo(), other.getMyFoo())
.append(myInt, other.myInt)
.isEquals();
}
}
public Bar createBar(...) {
//sensible implementation
}
public Bar createOtherBar(...) {
//another implementation
}
public boolean equals(Object o) {
//sensible equals implementation
}
}
Is there syntax by which I can refer to other's Foo reference apart from declaring the getMyFoo() method? Something like other.Foo.this (which doesn't work)?
No.
The best way is probably what you suggested: add a getFoo() method to your inner class.
No, not possible without a getter. The 'this' keyword will always point to the current instance. I'm quite curious why you would want to do this... seems like you are doing composition in the wrong way.
public class Foo {
public Bar createBar(){
Bar bar = new Bar(this)
return bar;
}
}
public class Bar {
Foo foo;
public Bar(Foo foo){
this.foo = foo;
}
public boolean equals(Object other) {
return foo.equals(other.foo);
}
}
Since using Foo.this limits creation of the inner class (Foo myFoo = new Foo(); myFoo.new Bar(); to an instance I'd say this is much cleaner.
yes:
public class Foo {
public class Bar {
public Foo getMyFoo() {
return Foo.this;
}
}
public Foo foo(Bar bar) {
return bar.getMyFoo();
}
public static void main(String[] arguments) {
Foo foo1=new Foo();
Bar bar1=foo1.new Bar();
Foo foo=(new Foo()).foo(bar1);
System.out.println(foo==foo1);
}
}

Categories

Resources