Converting int to Enum in Java reflection - java

This might look similar to a few other questions but so far I have not found a solution..
I am using reflection to parse my JSONs into different classes and it saves me a lot of effort from writing class-specific parsing code, all the ints, longs, strings, and Calendars etc are easy to deal with, but now I find myself in an hell of Enum specific castings
something like:
else if (field.getType().isAssignableFrom(TransactionType.class)){
field.set(representation, TransactionType.fromInt(Integer.parseInt(value, 10)));
}
the problem is that enums are stored as integers in the JSON, and I can not find a generic way to parse or cast those integers back to enums when I don't know what enum it specifically is, and I have quite a few enums so 70% of my parsing code are now dedicated to checking enum types...
is there a way that, given only field.getType().isEnum() == true, parse the int value to the enum type of that field
the enum type is declared as:
public static enum TransactionType{
cashback(0),deposit(1),withdraw(2),invitation(3);
public int code;
TransactionType(int code){
this.code = code;
}
private final static TransactionType[] map = TransactionType.values();
public static TransactionType fromInt(int n){
return map[n];
}
}
the JSON can be a bit complicated, but enum related fields has formats as:
{transactionType: 1, someOtherEnumType: 0}

Heres how I would approch this given the information provided. Use a helper method that would sit outside your enum types that can convert any enum type that implements some interface.
public static interface Codeable {
public int getCode();
}
public static enum TransactionType implements Codeable {
cashback(0),deposit(1),withdraw(2),invitation(3);
public int code;
TransactionType(int code) {
this.code = code;
}
#Override
public int getCode() {
return code;
}
}
public static <T extends Codeable> T fromCodeToEnum(int code, Class<T> clazz) {
for(T t : clazz.getEnumConstants()) {
if(t.getCode() == code) {
return t;
}
}
return null;
}
public static void main(String [] args) {
TransactionType type = fromCodeToEnum(1, TransactionType.class);
System.out.println(type); // deposit
}
Edit: Or of course you can just get the enum values and iterate through them. This could be placed wherever you want.
public static TransactionType findTransactionTypeByCode(int code) {
for(TransactionType t : TransactionType.values()) {
if(t.getCode() == code) {
return t;
}
}
return null;
}

Java do not support the implicit cast from literal to value.
Then enum in Java has method ordinal(), that returns int value.
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the >initial constant is assigned an ordinal of zero).
An unsafe solution
if(field.getType().isEnum()) {
Object itemInstance = field.getType().getEnumConstants()[ordinal];
}
How ever it is not recommended to us it at it was designed as part of API.
The recommendation for this case is to define in the definition of enum.
enum MyEnum {
ITEM(1);
private final int index;
MyEnum(int index) {
this.index;
}
}
And then you should implement additional logic to serialize and deserialize, based for example on interface with default method.
interface SerializableEnum<E extends Enum<E>> {
Class<E> getType();
default E valueOf(int ordinal) {
return getType().getEnumConstants()[ordinal];
}
}
Note that the best solution is to serialize the enum not via number but via its name.

Class.getEnumConstants() is what you need.
Class<?> cls = field.getType();
if (cls.isEnum()) {
field.set(representation,
cls.getEnumConstants()[Integer.parseInt(value, 10)]);
}

Related

Java enum method return generic type supplied in constructor?

I would like to have a generic return type for an enum method getValue(). The returned type should be the same as the one supplied in the constructor of the enum.
public enum ParameterType
{
NUMBER(int.class),
TEXT(String.class);
private Class<?> classType;
ParameterType(Class<?> _clazz)
{
classType = _clazz;
}
public <T> T getValue()
{
String a = "i am a text";
int b = 42;
return classType.cast(a);
//return classType.cast(b);
}
}
However, in this case the error is "cannot convert from capture #3 ? to T". Also, it is not possible to provide a generic "X" type on the enum itself which could be used for return types in case of classes.
How can I solve this problem?
Do forget about casting. Do redefine ‘getValue()’ for each enum constants.
You can't do this with an enum, because all values in an enum have the same type.
To do this, you have to basically build the "enum" by hand:
public final class ParameterType<T>
{
public static final ParameterType<Integer> NUMBER = new ParameterType<>(42);
public static final ParameterType<String> TEXT = new ParameterType<>("I am a text");
private ParameterType(T value) {
this.value = value;
}
public T getValue() { return value; }
}
An important point is to make the constructor private, so it can't be invoked outside the class. This makes it a bit like an enum, in that the instances you define are the only instances.

It is posible to improve this Java Generics scenario [duplicate]

I have a generic interface like this:
interface A<T> {
T getValue();
}
This interface has limited instances, hence it would be best to implement them as enum values. The problem is those instances have different type of values, so I tried the following approach but it does not compile:
public enum B implements A {
A1<String> {
#Override
public String getValue() {
return "value";
}
},
A2<Integer> {
#Override
public Integer getValue() {
return 0;
}
};
}
Any idea about this?
You can't. Java doesn't allow generic types on enum constants. They are allowed on enum types, though:
public enum B implements A<String> {
A1, A2;
}
What you could do in this case is either have an enum type for each generic type, or 'fake' having an enum by just making it a class:
public class B<T> implements A<T> {
public static final B<String> A1 = new B<String>();
public static final B<Integer> A2 = new B<Integer>();
private B() {};
}
Unfortunately, they both have drawbacks.
As Java developers designing certain APIs, we come across this issue frequently. I was reconfirming my own doubts when I came across this post, but I have a verbose workaround to it:
// class name is awful for this example, but it will make more sense if you
// read further
public interface MetaDataKey<T extends Serializable> extends Serializable
{
T getValue();
}
public final class TypeSafeKeys
{
static enum StringKeys implements MetaDataKey<String>
{
A1("key1");
private final String value;
StringKeys(String value) { this.value = value; }
#Override
public String getValue() { return value; }
}
static enum IntegerKeys implements MetaDataKey<Integer>
{
A2(0);
private final Integer value;
IntegerKeys (Integer value) { this.value = value; }
#Override
public Integer getValue() { return value; }
}
public static final MetaDataKey<String> A1 = StringKeys.A1;
public static final MetaDataKey<Integer> A2 = IntegerKeys.A2;
}
At that point, you gain the benefit of being a truly constant enumeration value (and all of the perks that go with that), as well being an unique implementation of the interface, but you have the global accessibility desired by the enum.
Clearly, this adds verbosity, which creates the potential for copy/paste mistakes. You could make the enums public and simply add an extra layer to their access.
Designs that tend to use these features tend to suffer from brittle equals implementations because they are usually coupled with some other unique value, such as a name, which can be unwittingly duplicated across the codebase for a similar, yet different purpose. By using enums across the board, equality is a freebie that is immune to such brittle behavior.
The major drawback to such as system, beyond verbosity, is the idea of converting back and forth between the globally unique keys (e.g., marshaling to and from JSON). If they're just keys, then they can be safely reinstantiated (duplicated) at the cost of wasting memory, but using what was previously a weakness--equals--as an advantage.
There is a workaround to this that provides global implementation uniqueness by cluttering it with an anonymous type per global instance:
public abstract class BasicMetaDataKey<T extends Serializable>
implements MetaDataKey<T>
{
private final T value;
public BasicMetaDataKey(T value)
{
this.value = value;
}
#Override
public T getValue()
{
return value;
}
// #Override equals
// #Override hashCode
}
public final class TypeSafeKeys
{
public static final MetaDataKey<String> A1 =
new BasicMetaDataKey<String>("value") {};
public static final MetaDataKey<Integer> A2 =
new BasicMetaDataKey<Integer>(0) {};
}
Note that each instance uses an anonymous implementation, but nothing else is needed to implement it, so the {} are empty. This is both confusing and annoying, but it works if instance references are preferable and clutter is kept to a minimum, although it may be a bit cryptic to less experienced Java developers, thereby making it harder to maintain.
Finally, the only way to provide global uniqueness and reassignment is to be a little more creative with what is happening. The most common use for globally shared interfaces that I have seen are for MetaData buckets that tend to mix a lot of different values, with different types (the T, on a per key basis):
public interface MetaDataKey<T extends Serializable> extends Serializable
{
Class<T> getType();
String getName();
}
public final class TypeSafeKeys
{
public static enum StringKeys implements MetaDataKey<String>
{
A1;
#Override
public Class<String> getType() { return String.class; }
#Override
public String getName()
{
return getDeclaringClass().getName() + "." + name();
}
}
public static enum IntegerKeys implements MetaDataKey<Integer>
{
A2;
#Override
public Class<Integer> getType() { return Integer.class; }
#Override
public String getName()
{
return getDeclaringClass().getName() + "." + name();
}
}
public static final MetaDataKey<String> A1 = StringKeys.A1;
public static final MetaDataKey<Integer> A2 = IntegerKeys.A2;
}
This provides the same flexibility as the first option, and it provides a mechanism for obtaining a reference via reflection, if it becomes necessary later, therefore avoiding the need for instantiable later. It also avoids a lot of the error prone copy/paste mistakes that the first option provides because it won't compile if the first method is wrong, and the second method does not need to change. The only note is that you should ensure that the enums meant to be used in that fashion are public to avoid anyone getting access errors because they do not have access to the inner enum; if you did not want to have those MetaDataKeys going across a marshaled wire, then keeping them hidden from outside packages could be used to automatically discard them (during marshaling, reflectively check to see if the enum is accessible, and if it is not, then ignore the key/value). There is nothing gained or lost by making it public except providing two ways to access the instance, if the more obvious static references are maintained (as the enum instances are just that anyway).
I just wish that they made it so that enums could extend objects in Java. Maybe in Java 9?
The final option does not really solve your need, as you were asking for values, but I suspect that this gets toward the actual goal.
If JEP 301: Enhanced Enums gets accepted, then you will be able to use syntax like this (taken from proposal):
enum Primitive<X> {
INT<Integer>(Integer.class, 0) {
int mod(int x, int y) { return x % y; }
int add(int x, int y) { return x + y; }
},
FLOAT<Float>(Float.class, 0f) {
long add(long x, long y) { return x + y; }
}, ... ;
final Class<X> boxClass;
final X defaultValue;
Primitive(Class<X> boxClass, X defaultValue) {
this.boxClass = boxClass;
this.defaultValue = defaultValue;
}
}
By using this Java annotation processor https://github.com/cmoine/generic-enums, you can write this:
import org.cmoine.genericEnums.GenericEnum;
import org.cmoine.genericEnums.GenericEnumParam;
#GenericEnum
public enum B implements A<#GenericEnumParam Object> {
A1(String.class, "value"), A2(int.class, 0);
#GenericEnumParam
private final Object value;
B(Class<?> clazz, #GenericEnumParam Object value) {
this.value = value;
}
#GenericEnumParam
#Override
public Object getValue() {
return value;
}
}
The annotation processor will generate an enum BExt with hopefully all what you need!
if you prefer you can also use this syntax:
import org.cmoine.genericEnums.GenericEnum;
import org.cmoine.genericEnums.GenericEnumParam;
#GenericEnum
public enum B implements A<#GenericEnumParam Object> {
A1(String.class) {
#Override
public #GenericEnumParam Object getValue() {
return "value";
}
}, A2(int.class) {
#Override
public #GenericEnumParam Object getValue() {
return 0;
}
};
B(Class<?> clazz) {
}
#Override
public abstract #GenericEnumParam Object getValue();
}

Method to accept any Enum and return all properties

I have the following Enum where I would like to create a method that will accept an Enum object, and return a comma separated list of the properties of that Enum. So for the following Enum, my method would accept it as a parameter and return a String of "1, 2".
public class typeEnum {
public enum validTypes{
TYPE1("1"),
TYPE2("2");
private String value;
validTypes(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static boolean contains(String type) {
for (validTypes msgType : validTypes.values()) {
if (msgType.value.equals(type)) {
return true;
}
}
return false;
}
}
}
My expected method would be something like the following:
public static <E extends Enum<E>, S extends String> String enumPropsToString(E enumClazz, S value) {
return ....
}
Enums can implement interfaces:
public interface ValuedEnum {
public String getValue();
}
public class SomeEnum implements ValuedEnum {
//your body from above
}
Then, you can use "intersection types" in your method signature:
public <T extends Enum<T> & ValuedEnum> String propsToString (Class<T> enumClass) {
Arrays.stream(enumClass.getEnumConstants()).map(e -> e.getValue()).collect(Collectors.joining(", "));
}
You could also do this via reflection - inspect the enumClass parameter of an arbitrary Enum for a Method with the getValue signature you want, and then reflectively call it; but this way is type-safe and sufficiently trivial that I'd strongly recommend doing this instead.
Reading your comments, if you want to allow an arbitrary property, then I'd suggest just using the Stream API:
public static <T> String propsToString (T[] values, Function<T, String> extractor) {
return Arrays.stream(values).map(extractor).collect(Collectors.joining(", "));
}
which can be invoked like this:
propsToString(MyEnum.values(), MyEnum::name);
Here is the method you need:
private static <E extends Enum<E>> String enumValues(Class<E> clazz) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method m = clazz.getMethod("values");
Object[] values = (Object[])m.invoke(null);
Method f = clazz.getMethod("getValue");
StringBuilder sb = new StringBuilder(f.invoke(values[0]).toString());
for (int i = 1 ; i < values.length ; i++) {
sb.append(", ");
sb.append(f.invoke(values[i]).toString());
}
return sb.toString();
}
Usage:
enum MyEnum {
X("A"), Y("B");
public String value;
MyEnum(String value) {
this.value = value;
}
}
// ...
System.out.println(enumValues(MyEnum.class));
// prints "A, B"
Explanation of how this works:
Instead of passing an enum instance to the method, you should pass a Class<E>. This makes it easier for reflecting stuff from it. It also makes it easier to call the method as you don't need to create a new enum instance.
First, we need to get all the values of the enum class passed in. To do this we get the method values from the enum class and call it. Here I stored all the values in a variable called values.
I then got the method getValue from the enum class. In the comments you said that when an enum does not have a value field it should not be passed into this method. I assume you mean you don't care about non-existent value fields and you trust the caller. That's why I didn't do any checks here.
After that I used a string builder and for loop to concatenate the value of value for each of the enum values.
Phew that was long!
Note that this method is extremely unsafe. You should probably use interfaces like the other answers have said. But hey, this is fun, and you seem confident that you won't pass anything invalid in there. :)

Java: Generic method for Enums

Help me understand generics. Say I have two enums as inner classes like so:
public class FoodConstants {
public static enum Vegetable {
POTATO,BROCCOLI,SQUASH,CARROT;
}
public static enum Fruit {
APPLE,MANGO,BANANA,GUAVA;
}
}
Instead of having both enums implement an interface, and have to implement the same method twice, I would like to have a method in the outer class that does something like:
public <e> String getEnumString<Enum<?> e, String s) {
for(Enum en: e.values()) {
if(en.name().equalsIgnoreCase(s)) {
return s;
}
}
return null;
}
However this method does not compile. What I am trying to do is find out if a string value is the name of an enumerated value, in ANY enum, whether it's Vegetable, Fruit, what not.
Regardless of whether this is in fact a redundant method, what is wrong with the one I am trying to (re)write?
Basically I would like to do this:
public class FoodConstants {
public static enum Vegetable {
POTATO,BROCCOLI,SQUASH,CARROT;
}
public static enum Fruit {
APPLE,MANGO,BANANA,GUAVA;
}
public <e> String getEnumString<Enum<?> e, String s) {
for(Enum en: e.values()) {
if(en.name().equalsIgnoreCase(s)) {
return s;
}
}
return null;
}
} //end of code
public static <E extends Enum<E>>
String getEnumString(Class<E> clazz, String s){
for(E en : EnumSet.allOf(clazz)){
if(en.name().equalsIgnoreCase(s)){
return en.name();
}
}
return null;
}
The original has a few problems:
It accepts an instance of the enum instead of the class representing the enum
which your question suggests you want to use.
The type parameter isn't used.
It returns the input instead of the instance name. Maybe returning the instance would be more useful -- a case-insensitive version of Enum.valueOf(String).
It calls a static method on an instance so you can iterate. EnumSet does all the reflective stuff for you.

Passing enums through aidl interfaces

As enums aren't primitive types, what's the most effective way to pass an enum through an aidl interface in Android? Is there a way to convert the enum to an ordinal first?
I simply use
String enumString = myEnum.name()
(with MyEnum as enum and myEnum as value) to get the String representation and then
MyEnum myEnum = MyEnum.valueOf(enumString)
to reconstruct the enum from the String representation.
Using Ordinals may be a wee bit faster but if I may add Enums later, this is more likely to break old code.
//Edit: As I don't like to have String as return type, I now implemented Parcellable like mentioned here: Passing enum or object through an intent (the best solution)
import android.os.Parcel;
import android.os.Parcelable;
enum InitResponse implements Parcelable {
// Everything is fine.
SUCCESS,
// Something else
FOO;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeString(name());
}
public static final Creator<InitResponse> CREATOR = new Creator<InitResponse>() {
#Override
public InitResponse createFromParcel(final Parcel source) {
return InitResponse.valueOf(source.readString());
}
#Override
public InitResponse[] newArray(final int size) {
return new InitResponse[size];
}
};
}
Non primitive types, other than String, require a directional indicator. Directional indicators include in, out and inout.
Take a look at the official documentation for that: http://developer.android.com/guide/developing/tools/aidl.html#aidlsyntax
Also, you can consider passing the String or ordinal representation of the enum and translate it back when needed. This is taken from the Effective Java 2nd edition:
// Implementing a fromString method on an enum type
private static final Map<String, Operation> stringToEnum = new HashMap<String, Operation>();
static { // Initialize map from constant name to enum constant
for (Operation op : values())
stringToEnum.put(op.toString(), op);
} // Returns Operation for string, or null if string is invalid
public static Operation fromString(String symbol) {
return stringToEnum.get(symbol);
}
In the case above, Operation is an enum.
To get the ordinal of an enum consider this example:
public enum Badges{
GOLD, SILVER, BRONZE;
}
// somewhere else:
int ordinal = Badges.SILVER.ordinal();// this should be 1
Yes, you can pass enums through AIDL, but you do have to implement Parcelable on the enum type.
1: A Parcelable implementation.
public enum RepeatMode implements Parcelable {
NoRepeat,
RepeatAll,
RepeatTrack,
;
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(toInteger());
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<RepeatMode> CREATOR = new Creator<RepeatMode>() {
#Override
public RepeatMode createFromParcel(Parcel in) {
return RepeatMode.fromInteger(in.readInt());
}
#Override
public RepeatMode[] newArray(int size) {
return new RepeatMode[size];
}
};
public int toInteger() { return this.ordinal(); }
public static RepeatMode fromInteger(int value)
{
return values()[value];
}
}
An import:
RepeatMode.aidl:
package com.cyberdyne.media;
parcelable RepeatMode;
And remember to mark enum arguments as in arguments.
Kind of obvious when you think about it. But I'm betting Google doesn't use a whole lot of enums in IBinder interfaces. I do it though. (Thank you Android studio for providing "Implement Parcelable", which doesn't work entirely for enums, but makes things relatively easy).
Discursus on Android enums:
Best practice recommendations against enums in Android were withdrawn many moons ago. You're trading about 200 bytes of executable for horrible horrible code. Phones have come a long way since Android 1.0. It's a no-brainer. Use enums. (Or use the insane Kotlin-driven attribute system that Google uses. Good luck with that.)
Official Java Lore dating back to the Original Java language spec discourages the use of naked ordinal(). The reasoning: maintainers in the deep future may unwittingly re-order the ordinals and break stuff. Frankly, I think that's pompous Java bogosity. I struggled with this for a long time, and after much soul-searching, I caved in.
public enum Badges {
GOLD,SILVER, BRONZE; // Must match #array/badge_states
public int toInteger() { return this.ordinal(); }
public static Badges fromInteger(int value) { return values()[value]);
}
If nothing else, it marks the class as one that probably persists integers. And a comment never hurts, and it makes the receiving end of marshalled enums a bit prettier (and just a tiny bit safer).

Categories