Java – what is the best way to verify multiple instanceof with basic types (for example, switch case)?
I searched the answer here, and every post I found is actually the "fragment" I am looking for
I want to find a better way than this:
~ editor: Oh! I mean to use the original wrapper class first, but when I called the method at that time, I was considering using the original type ~ 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);
Note the @ override annotation: This is the implementation of the interface method This method will accept different types according to the implementation, so I don't want to create three different methods with different parameter types
In this example, this is a text box that accepts only numbers and nothing else, so it can only be represented by a string (verified by the regular expression ^ [0-9] * $), long and int
I also like it – maybe, eventually – to accept custom (and simple) DTOs that are more like POJOs, but if this particularity complicates everything else, I will consider other factors, so don't worry too much about this one
As I said, different implementations of this interface can accept completely different types
*I obviously don't want a way to switch integers, long integers and strings (it can't be switched, but until Java 7), I want to switch instanceofs*
After reading it
> java: boolean instanceOf Boolean? > switch instanceof? > Auto@R_804_2419 @ing: http://leepoint.net/notes-java/data/basic_types/autoboxing.html
My implementation is obviously effective, but I think there is a better way I want to know if there is a cleaner method than I do. Do you have any suggestions and reasons?
Thank you for your time Sincerely, Dominic Brissette
Editing: using original types and Auto@R_804_2419 @ing
public static void main(String[] args) { int i = 42; System.out.println(auto@R_804_2419@ing(i)); } public static boolean auto@R_804_2419@ing(Object o) { return o instanceof Integer; }
The output is true, because finally, Myint instanceof integer is a little true
Solution
One thing you can do is wrap primitives in an interface so that any value type that implements this interface can be passed as a value
public interface ValueInterface { processValue(); }
Then the set value method looks like:
public void setValue(ValueInterface value) { value.processValue(); }
Now you delegate your work to a real person who knows how to act on yourself