Is it possible in Java to return the enum value without having to call a function to return the value, such as getFlag() in my example? If so, how?
public enum MessageFlags {
BIT0((short)1),
BIT1((short)2),
BIT2((short)4),
BIT3((short)8),
BIT4((short)16),
BIT5((short)32),
BIT6((short)64),
BIT7((short)128),
BIT8((short)256),
BIT9((short)512),
BIT10((short)1024),
set_freq(BIT0),
get_freq(BIT1);
short bitFlag = 0;
MessageFlags flag;
MessageFlags(short flag) {
this.bitFlag = flag;
}
MessageFlags(MessageFlags flag) {
this.flag = flag;
}
public short getFlag() {
return this.flag.bitFlag;
}
public short getValue() {
return this.bitFlag;
}
}
Just say MessageFlags.BITX and that will return the same value as getFlag()
You can import static MessageFlags.*; and say BITX.getFlag().
Here is a complete example:
A.java
package foo;
import static foo.B.*;
public class A{
public B value = BAR;
}
B.java
package foo;
public enum B{
BAR, BAZ, BOO
}
I followed #Jeremy's advice of this:
package foo;
import static foo.B.*;
and then I created a method called set_freq in my MessageFlags enum. I made this function static and had it return short. For example,
public static short set_freqflag() {
return BIT0.getFlag();
}
The semantics of set_freqflag are a little weird because you are not setting anything but I do not have a better name at the moment. This allows me to just state set_freqflag() rather than the longer way I was doing before.
I might be really late, but I'm writing to anyone who visits this topic for help.
If you have an enum, and you'd like to return a specific parameter of its values by default without calling a get function, you need to insert an #Override above your selected function, like:
public class Plants {
public enum Fruits {
APPLE ("sweet"),
GRAPEFRUIT ("sour");
private String taste;
Fruits (String taste) {
this.taste = taste;
}
#Override
public String getTaste() {
return this.taste;
}
}
}
And now you can call whichever enum value you'd like, without a get function:
Plants.Fruits.APPLE
And it'll return "sweet"
P.S. I'm not a professional programmer, please correct me if I've written something anti-conventional by accident.
Related
I want to refactor old code that uses a class of constants to enum, the code is already being used in a several places inside the code.(I know it's possible in eclipse, but haven't found it on IntelliJ Refactoring Dialogs)
Current State:
public class MyConstants {
public static String MY_CONSTANT_1 = "MY_CONSTANT_1_VALUE";
public static String MY_CONSTANT_2 = "MY_CONSTANT_2_VALUE";
public static String MY_CONSTANT_3 = "MY_CONSTANT_3_VALUE";
}
public class MyClass {
//usage of constant
if (mString.equals(MyConstants.MY_CONSTANT_1)){}
}
Expected result:
enum MyEnum {
MY_CONSTANT_1("MY_CONSTANT_1_VALUE"),MY_CONSTANT_2("MY_CONSTANT_2_VALUE"),MY_CONSTANT_3("MY_CONSTANT_3_VALUE")
private final String value;
MyEnum(String aValue){
value = aValue;
}
public String getValue(){
return value;
}
}
public class MyClass {
//usage of constant
if (mString.equals(MyConstants.MY_CONSTANT_1.getValue())){}
}
Note: I know Android official documentation recommend not to use enum but this is not my question.
You can't do it with Android Studio automatically.
In preparing for an interview, someone mentioned knowing how to make a class/method in java read-only. I've been doing a bit of searching, but haven't found anything really concrete.
Maybe this question is simpler to answer than I'm making it out to be, but what would be a way to make a class or method read-only in java?
The following code will ensure that your class is always READ ONLY, but if you find any loop hole, please post it here.
import java.io.Serializable;
final public class ImmutableClass implements Cloneable,Serializable {
private static final long serialVersionUID = 6488148163144293060L;
private static volatile ImmutableClass instance;
private ImmutableClass() {
// no-op
System.out.println("instance created : " + this.hashCode());
}
/**
* Lazy Instantiation
*
* #return
*/
public static ImmutableClass getInstance() {
if (instance == null) {
synchronized (ImmutableClass.class) {
System.out.println("aquired lock");
if (instance == null) {
instance = new ImmutableClass() {
};
}
System.out.println("released lock");
}
}
return instance;
}
public Object readResolve() {
System.out.println("readResolve()");
return getInstance();
}
#Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
The Read-only class means, we are talking about "IMMUTABLE" concept.
The following example depicts the same:
public class ImmutableString {
static String upcase(String s) {
return s.toUpperCase(); // here local variable s vanishes
// it return the value to a new String object
}
public static void main(String[] args) {
String s = new String("abc");
System.out.println(s); //abc
String s1 = upcase(s);
System.out.println(s1); //ABC
System.out.println(s); //abc
}
}
Lets Say you want a read only version of an object,
case 1: if your class contains fields which are not pointers to any other objects eg:
public class Person{
private String name;
//Getters n Setters
}
in this case, you can return a copy of this class, write a constructor that accepts Person, any one who wants to get a Person object will have a copy of this object so any Setter operations wont effect the original object(Strings are immutable)
Case 2: in case your object contains a pointer to another object or list or map
in this case make classes implement an interface which has only read-only methods(Getters) and wherever you are returning the object, change it to return this interface, so client will have access to only read-only methods
eg:
class Person implements ReadOnly{
String name;
.. assume pointers also in here
// Getter n Setters
public PersonReadOnly(){
return this;
}
}
interface PersonReadOnly {
public String getName();
}
Simple rule: Don't have any public fields and No public setter methods.
For example, see class below:
final class AReadOnlyClass
{
private int anInt;
public int GetAnInt()
{
return anInt;
}
}
I need to use an Enum with a combobox (values shown below).
YES (shown as YES on UI, stored in DB as Y)
NO (shown as NO on UI, stored in DB as N)
DEFAULT (shown as "" on UI, stored in DB as null)
The Enum has methods to perform the following -
toString() - to provide the custom String for UI. (showing the combo options)
OptionToDB (static) - Convert a selected option to db value (on save / update)
DBToOption (static)- Convert a DB value to selcted option (while loading the screen)
static enum EnumOption{
YES,NO,DEFAULT;
....
public static EnumOption DBToOption(String val){
if("Y".equals(val)){
return YES;
} else if("N".equals(val)){
return NO;
}else {
return DEFAULT;
}
}
....
}
It works pretty well, but the issue with above methods is that it uses if/else comparison to deduce which option / db value to be returned.
I thought of storing the dbValue as a field in enum but I was not able to reduce the if/else from DBToOption.
Can this if/else be avoided in any way using a better design??
If you store the dbValue as a field in the enum, you can remove the if/else and replace it with a for-loop, although I don't see anything wrong with those if/elses for this particular case:
static enum EnumOption {
YES("Y"),
NO("N"),
DEFAULT("");
private final String value;
private EnumOption(String value) {
this.value = value;
}
public static EnumOption DBToOption(String val) {
for (EnumOption opt : EnumOption.values()) {
if (opt.value.equals(val)) {
return opt;
}
}
return DEFAULT;
}
}
public enum EnumOption {
YES("Y"), NO("N"), DEFAULT("");
private final String value;
private final static Map<String, EnumOption> options;
static {
options = new HashMap<String, EnumOption>();
for (EnumOption opt : EnumOption.values()) {
options.put(opt.value, opt);
}
}
private EnumOption(String value) {
this.value = value;
}
public static EnumOption DBToOption(String val) {
return options.get(val) != null ? options.get(val) : DEFAULT;
}
}
And here is the test that proves it works.
public void testDBToOption() {
assertEquals(EnumOption.NO, EnumOption.DBToOption("N"));
assertEquals(EnumOption.YES, EnumOption.DBToOption("Y"));
assertEquals(EnumOption.DEFAULT, EnumOption.DBToOption(""));
assertEquals(EnumOption.DEFAULT, EnumOption.DBToOption(null));
assertEquals(EnumOption.DEFAULT, EnumOption.DBToOption("R"));
}
So you want to get rid of the remaining if/else ...Are you doing Object Calisthenics?
You could do the following, if you do not have compatibility issues:
public enum EnumOption {
Y("Y", "YES"),
N("N", "NO"),
D("D", "");
private final String dbValue;
private final String uiValue;
private EnumOption(String dbValue, String uiValue) {
this.dbValue = dbValue;
this.uiValue = uiValue;
}
public String getDbValue() {
return this.dbValue;
}
public String uiValue() {
return this.uiValue;
}
public static EnumOption getFromDb(String dbValue) {
return EnumOption.valueOf(dbValue);
}
}
Since each enum value can only occur once, this has at least the same performance as all the other implementations.
For details about the automatically generated valueOf(String) method in enum types, and James DW's solution, you can read up in Josh Bloch's Effective Java Item 30 (Use enums instead of int constants), page 154.
Javadoc for Class.getFields() say: "The elements in the array returned are not sorted and are not in any particular order."
Any hints on how the order actually is determined? Is it possible that when I execute this method twice, I get fields in different order? In other words, is the order stable for given compiled class, or even between compilations of the same source file?
It should be stable, and for Oracle's JVM its the order they are declared, but you should not rely on this.
You should base lookup on the field's name (and possibly declaring class) rather than position.
On my JVM, at least,
Class.getFields() returns fields in declaration order.
Class.getMethods(), on the other hand, doesn't always. It returns them in (I believe) the order the classloader sees the strings. So if two classes have the same method name, the second-loaded class will return the shared method name before its other methods.
javap confirms the compiler wrote both fields and methods in declaration order.
See the output of this code sample.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class OrderTest {
public static void main(String[] args) {
// fields are in declaration order
for (Field field : C1.class.getDeclaredFields()) {
System.out.println(field.getName());
}
for (Field field : C2.class.getDeclaredFields()) {
System.out.println(field.getName());
}
// methods, on the other hand, are not necessarily in declaration order.
for (Method method : C1.class.getDeclaredMethods()) {
System.out.println(method.getName());
}
for (Method method : C2.class.getDeclaredMethods()) {
System.out.println(method.getName());
}
}
}
class C1 {
public int foo;
public int bar;
public int getFoo() { return foo; }
public int getBar() { return bar; }
}
class C2 {
public int bar;
public int foo;
public int getBar() { return bar; }
public int getFoo() { return foo; }
}
on my JVM (1.7.0_45, Windows) this returns
foo
bar
bar
foo
getFoo
getBar
getFoo
getBar
Create a helper method that returns a sorted list, and use that instead whenever you need the list of fields. Or lookup by name instead of index.
An natural order of properties offers the Ujorm framework with its key-value objects using the readKeys() method.
Each item of the result have got similar features like the Field including reading and writting values from/to the object. For example see the next code:
public class User extends AbstractUjo implements Serializable {
/** Factory */
private static final KeyFactory<User> f = newFactory(User.class);
/** Keys: */
public static final Key<User, Long> PID = f.newKey();
public static final Key<User, Integer> CODE = f.newKey();
public static final Key<User, String> NAME = f.newKey();
public static final Key<User, Double> CASH = f.newKey();
static {
f.lock();
}
// Setters:
public void setPid(Long pid) {
PID.setValue(this, pid);
}
public void setCode(Integer code) {
CODE.setValue(this, code);
}
public void setName(String name) {
NAME.setValue(this, name);
}
public void setCash(Double cash) {
CASH.setValue(this, cash);
}
// Getters ...
}
The natural order of keys can be iterated by:
for (Key key : new User().readKeys()) {
System.out.println("Key: " + key);
}
See the documentation for more information.
I have an enum that looks like
public enum MyEnum
{
myValue
{
#Override
public String myMethod(String dostuff)
{
return dostuff + "One";
}
},
myOtherValue
{
#Override
public String myMethod(String dostuff)
{
return dostuff + "Two";
}
},
aThirdValue
{
#Override
public String myMethod(String dostuff)
{
return dostuff + "Three";
}
};
public abstract String myMethod(String dostuff);
}
Now I think we can all agree that this looks horrible?
but what would be the bether way? I could have an abstractfactory, but then i would need three implementationclasses that each as a one line method. Dont find that so pretty either. I could use a switch (either in the code or in the enum). But then i could forgett to add a case.
So, whats the way to go? There must be a pattern for this, but cant seem to find one.
The best ive come up with so far is to add comments to autocollapse the methods in Netbeans, not so brilliant that either.
The solution is to create a private constructor for the enum:
public enum MyEnum
{
myValue("One"), myOtherValue("Two"), aThirdValue("Three");
private String value;
private MyEnum(String value) { this.value = value; }
public String myMethod(String dostuff)
{
return dostuff + value;
}
}
[EDIT] Note that you can pass more complex things in. For example, you can pass in a class which implements a certain interface (say Work which has a method doWork()). This way, you can store method calls in enums to do different kinds of work.
Check out the command pattern or maybe the strategy pattern.
It's ugly, but most solutions to non-trivial extensions of the problem are just going to move the ugliness around.
For instance, you could encapsulate the three different behaviors in three different implementations of some interface, and then pass a different behavior implementation to the constructor of each enum. (This is basically the command or strategy approach that others are suggesting).
If you make these implementations, and the interface, separate classes, then you've potentially exposed that behavior beyond the enum, which is unnecessary and arguably ugly.
If you make them private static inner classes of the enum, you've moved the ugliness from the top of the file to the bottom of the file. How much less ugly this is is in the eye of the beholder.
public enum Foo {
ONE(new OneDelegate()),
TWO(new TwoDelegate()),
THREE(new ThreeDelegate());
// ////////////////////
// Private stuff
private final FooDelegate delegate;
private Foo(FooDelegate delegate) {
this.delegate = delegate;
}
// ////////////////////
// Public methods
public String doStuff(String stuff) {
return delegate.doStuff(stuff);
}
// ////////////////////
// Helper classes
private static interface FooDelegate {
String doStuff(String stuff);
}
private static class OneDelegate implements FooDelegate {
#Override
public String doStuff(String stuff) {
return "One " + stuff;
}
}
private static class TwoDelegate implements FooDelegate {
#Override
public String doStuff(String stuff) {
return "Two " + stuff;
}
}
private static class ThreeDelegate implements FooDelegate {
#Override
public String doStuff(String stuff) {
return "Three " + stuff;
}
}
}
The other obvious solution is to put all three behaviors in as private methods, and put a switch(this) in the public method. Personally, I think this is ugly as sin, but a lot of ex-C programmers seem to like it. :)
public enum Foo {
ONE, TWO, THREE;
// ////////////////////
// Public methods
public String doStuff(String stuff) {
switch(this) {
case ONE:
return doStuffOne(stuff);
case TWO:
return doStuffTwo(stuff);
case THREE:
return doStuffThree(stuff);
// If we're handing all enum cases, we shouldn't need
// a default (and per comments below, if we leave out
// the default, we get the advantage that the compiler
// will catch it if we add a new enum value but forget
// to add the corresponding doStuff() handler
// default:
// throw new IllegalStateException("Who am I?");
}
}
// ////////////////////
// Static helpers
private static String doStuffOne(String stuff) {
return "One " + stuff;
}
private static String doStuffTwo(String stuff) {
return "Two " + stuff;
}
private static String doStuffThree(String stuff) {
return "Three " + stuff;
}
}
What about?
public enum MyEnum {
myValue("One"),
myOtherValue("Two"),
aThirdValue("Three");
private final String postfix;
private MyEnum(String postfix) {
this.postfix )= postfix;
}
public String myMethod(String dostuff) {
return dostuff + postfix;
}
}
Even if your real stuff is more complex, there are several techniques that allow such improvements. Please post your real need...