Return different type of data from a method in java?

前端 未结 13 1451
别那么骄傲
别那么骄傲 2020-12-05 02:18
public static void main(String args[]) {
    myMethod(); // i am calling static method from main()
 }

.

public static ? myMethod(){         


        
相关标签:
13条回答
  • 2020-12-05 03:11

    Method overloading can come in handy here Like:

    <code>
    public class myClass 
    {
        int add(int a, int b) 
        {
             return (a + b);
        }
    
        String add(String a, String b)
        {
             return (c + d);
        }
    
        public static void main(String args[]) 
        {
            myClass ob1 = new myClass);
            ob1.add(2, 3);
            //will return 5
            ob1.add("Hello, ", "World!");
            //will return Hello, World!
        }
    
    }
    

    0 讨论(0)
  • 2020-12-05 03:13

    you can have the return as an object. You create that object 'on fly' in your

    function: if(int) 
     return new object(){
       int nr=..
    }
    

    same for string. But I am concerned that is an expensive solution...

    0 讨论(0)
  • 2020-12-05 03:14

    I just want to put my view

    So you need to create a generic Return type and implemented by different types of concret return types. The Service class can create different types of objects concrete class and return as a generic type.

    public interface GenericReturnType{
        public static RETURN_TYPE enum{
            MACHINE, PERSON;    
        }
        public RETURN_TYPE getReturnType();
    }
    
    public class PersonReturnType implements GenericReturnType{
        // CONSTRUCTORS //
    
        // GETTRE AND SETTER //
    
        public RETURN_TYPE getReturnType(){
            return PERSON;
        }
        public String getAddress(){
            return something;
        }
    }
    
    public class MachineReturnType implements GenericReturnType{
        // CONSTRUCTORS //
    
        // GETTRE AND SETTER //
    
        public RETURN_TYPE getReturnType(){
            return MACHINE;
        }
        public String getManufatureName(){
            return something;
        }
    }
    
    
    public class TestService{
        public GenericReturnType getObject(// some input //){
            GenericReturnType obj ;
            if(// some code //){
                obj = new  PersonReturnType();
                // some code //
            }
            if(// some code //){
                obj = new  MachineReturnType();
                // some code //
            }
            return obj;
        }
    }
    
    public class TestDriver{
        TestService service = new TestService();
        GenericReturnType genObj = TestService.getObject(// some input //);
        if(genObj.getReturnType() == RETURN_TYPE.MACHINE){
            // SOME CODE // 
        }
        if(genObj.getReturnType() == RETURN_TYPE.PERSON){
            // SOME CODE // 
        }
    }
    
    0 讨论(0)
  • 2020-12-05 03:14
    
    public ArrayList divineCast(String object) {  
            try
            {
                Integer result = Integer.parseInt(object);
                ArrayList<Integer> generic = new   ArrayList<Integer>();
                generic.add(result);
                return generic;
            }
            catch(Exception e)
            {
                //not a Integer
            }
            try
            {
                Float result = Float.parseFloat(object);
                ArrayList<Float> generic = new   ArrayList<Float>();
                generic.add(result);
                return generic;
            }
            catch(Exception e)
            {
                //not a Float
            }
            try
            {
                Double result = Double.parseDouble(object);
                ArrayList<Double> generic = new   ArrayList<Double>();
                generic.add(result);
                return generic;
            }
            catch(Exception e)
            {
                //not a double
            }
            try
            {
                Boolean result = Boolean.parseBoolean(object);
                ArrayList<Boolean> generic = new   ArrayList<Boolean>();
                generic.add(result);
                return generic;
            }
            catch(Exception e)
            {
                //not a Boolean
            }
            try
            {
                String result = String.valueOf(object);
                ArrayList<String> generic = new   ArrayList<String>();
                generic.add(result);
                return generic;
            }
            catch(Exception e)
            {
                //not a String
            }
            return null;
    
        }
    

    Then you can call then function as so

    String test1 = "0.90854938";
    String test2 = "true";
    System.out.println(divineCast(test1).get(0));
    System.out.println(divineCast(test1).get(0).getClass());
    System.out.println(divineCast(test2).get(0));
    System.out.println(divineCast(test2).get(0).getClass());
    

    Java doesn't force you to declare the type of ArrayList you are returning in the function declaration, so you can return an ArrayList of any type.

    0 讨论(0)
  • 2020-12-05 03:15

    I create various return types using enum. It doesn't defined automatically. That implementation look like factory pattern.

    public  enum  SmartReturn {
    
        IntegerType, DoubleType;
    
        @SuppressWarnings("unchecked")
        public <T> T comeback(String value) {
            switch (this) {
                case IntegerType:
                    return (T) Integer.valueOf(value);
                case DoubleType:
                    return (T) Double.valueOf(value);
                default:
                    return null;
            }
        }
    }
    

    Unit Test:

    public class MultipleReturnTypeTest {
    
      @Test
      public void returnIntegerOrString() {
         Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
         Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
      }
    
    }
    
    0 讨论(0)
  • 2020-12-05 03:15

    This can be one of the solution. But your present solution is good enough. You can also add new variables and still keep it clean, which cannot be done with present code.

    private static final int INDEX_OF_STRING_PARAM = 0;
    private static final int INDEX_OF_INT_PARAM = 1;
    
    public static Object[] myMethod() {
        Object[] values = new Object[2];
        values[INDEX_OF_STRING_PARAM] = "value";
        values[INDEX_OF_INT_PARAM] = 12;
        return values;
    }
    
    0 讨论(0)
提交回复
热议问题