Skip to content
Advertisement

Assigning datatype to a generic type of variable based on a condition in Java

I have a usecase of supporting multiple datatypes for same variable. So tried to use Generics. For example

class Test<T> {
    T defaultValue;
    String value;
}

class TestImpl {
    private void test(String datatype ){
        Test<?> test = null;
        if (datatype.equals("Integer")) {
            test = new Test<Integer>();
            test.setDefaultValue(3); // I get some issues while doing this statement
        }
        if (datatype.equals("String")) {
            test = new Test<String>();
            test.setDefaultValue("dummy");
        }
        // some other actions common for all possible data types 
    }
}

The above code does not work. Can anyone please suggest a good way of doing it?

Advertisement

Answer

I changed the class names.

class SOQ<T>
{

   T defaultValue;
   String value;
   
}

class SOQ_Impl
{

   private void test(String datatype)
   {
   
      switch (datatype)
      {
      
         case "Integer": {
            SOQ<Integer> test = new SOQ<>();
            test.defaultValue = 3;
            actionsCommonForAllPossibleDataTypes(test);
            break;
         }
      
         case "String": {
            SOQ<String> test = new SOQ<>();
            test.defaultValue = "dummy";
            actionsCommonForAllPossibleDataTypes(test);
            break;
         }
      
      }
      
   }
   
   private void actionsCommonForAllPossibleDataTypes(SOQ<?> test)
   {
   
         // some other actions common for all possible data types 
   
   }
   
}

You declared the type with a <?> parameter, and that is what is causing you problems. I resolved this by not declaring the variable I was going to use until after I knew what type I wanted it to be.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement