Can I pass a primitive type by reference in Java?

后端 未结 9 1768
粉色の甜心
粉色の甜心 2021-02-05 22:58

I would like to call a method which could potentially take on different versions, i.e. the same method for input parameters that are of type:

  • boolean
  • byte
9条回答
  •  野性不改
    2021-02-05 23:24

    Yes, please be more specific about what you want to achieve. From your description I suggest you have a look at Java generics where you could write something like this:

    class SomeClass  {
      GenericType val;  
    
      void setValue(GenericType val) {
         this.val = val;
      }
    
      GenericType getValue() {
         return val;
      }
    
      public static void main(String[] args) {
        SomeClass myObj = new SomeClass();
        myObj.setValue(5);
        System.out.println(myObj.getValue());
    
        SomeClass myObj2 = new SomeClass();
        myObj2.setValue("hello?!");
        System.out.println(myObj2.getValue());
    
      }
    
    }
    

提交回复
热议问题