I've searched for answers here and every thread I found were in fact "fragments" of what I seek.
I'd like to find a better way than this :
~ EDIT: OOPS ! I meant to use primitive Wrapper classes in the first place, but I was thinking of using primitive types when calling the method at that very moment~ Thank you for noticing it :)
@Override
public void setValue(Object value) {
if (value instanceof String) {
} else if (value instanceof Integer) { // and not 'int'
} else if (value instanceof Long) { // and not 'long'
}
}
// The usage that made me confused in the first place :
int i = 42;
setValue(i);
Notice the @Override annotation: this is an implementation of an interface method. This method would accept different types based on the implementation so I don't want to create three disctinct methods using different parameter types.
In this example, this is a textbox that only accepts digits and nothing else, so it can only be represented by a String (which is validated by a Regular Expression ^[0-9]*$
), a long and an int.
I'd also like it to - maybe, eventually - accept custom (and simple) DTO's that are more like POJOs, but if this particularity makes everything else complicated I've got something else in mind so don't worry too much about this one.
As I said, different implementations of this interface could accept totally different types.
* I am obviously not asking a way to switchcase Integers, Longs and String (which cannot be switchcased, yet. Not until Java7 that is), I want to switchcase the instanceofs *
After looking at
- java: boolean instanceOf Boolean?
- switch instanceof?
- Autoboxing : http://leepoint.net/notes-java/data/basic_types/autoboxing.html
My implementation obviously works, but I just feel there's a better way. I am wondering if there is a cleaner method than doing what I did, what do you suggest and why?
Thank you for your time. Sincerely, Dominic Brissette.
EDIT: usage with primitive types and Autoboxing
public static void main(String[] args) {
int i = 42;
System.out.println(autoboxing(i));
}
public static boolean autoboxing(Object o) {
return o instanceof Integer;
}
Outputs true
because in the end, myInt instanceof Integer
is kinda true ..!