Creating an object with String overload and method

I have a String, which can be either of type Double, or Integer, or of another type. First I need to create a Double or Integer object, and then send it to the overloaded method. Here is my code so far;

public void doStuff1(object obj, String dataType){

 if ("Double".equalsIgnoreCase(dataType)) {
        doStuff2(Double.valueOf(obj.toString()));
    } else if ("Integer".equalsIgnoreCase(dataType)) {
        doStuff2(Integer.valueOf(obj.toString()));
    }

 }

 public void doStuff2(double d1){
   //do some double related stuff here
 }

 public void doStuff2(int d1){
   //do some int related stuff here
 }

I would like to do this without if / else, with something like this:

Class<?> theClass = Class.forName(dataType);

The problem is that "theClass" still cannot be added to either double or int. I would appreciate any ideas. Thank.

Find the connected stream; Java overload and multiple submission

+5
source share
4 answers

This is not just a matter of handling primitive types.

, , , (, if-).

, , doStuff2 Integer Double ( , ).

( , Java . , , .)

+5

aioobe, .

, . :

  • , doStuff2.
  • , doStuff2.
  • , () .
  • , , ... , "" .

, . .


, - . if/else ( String Java 7), - .

Map<String, Operation> map = ...
map.put("Double", new Operation(){
    public void doIt(Object obj) {
        doStuff2((Double) obj);
    }});
map.put("Integer", new Operation(){
    public void doIt(Object obj) {
        doStuff2((Integer) obj);
    }});
...
map.get(typeName).doIt(obj);

... "" .

+1

, , . , . , yourMethod() .

+1

, . , , . , double, double.class.

+1

All Articles