Explicit vs implicit call of toString

前端 未结 5 872
日久生厌
日久生厌 2020-12-01 04:31

I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.

For i

5条回答
  •  死守一世寂寞
    2020-12-01 05:00

    It is quite easy to write a generic reference type.

    class ref
    {
      static public class Reference
      {
        private T value;
        public Reference(T value) { set(value); }
        public Reference() { set(null); }
        public void set (T value) { this.value = value; }
        public T get () { return this.value; }
        public String toString() { return String.valueOf(this.value); }
      }
    
      static void fillString (Reference str)
      {
        str.set("foo");
      }
    
      public static void main (String[] args)
      {
        Reference str = new Reference("");
        fillString(str);
        System.out.println (str);
      }
    }
    

    Running it gives the required output:

    javac ref.java && java ref
    foo
    

提交回复
热议问题