Synthetic Class in Java

后端 未结 13 1765
广开言路
广开言路 2020-11-29 17:15

What is a synthetic class in Java? Why should it be used? How can I use it?

13条回答
  •  情书的邮戳
    2020-11-29 17:35

    A synthetic class does not appear in your code: it is made up by compiler. E.g. A bridge method made up by compiler in java is typically synthetic.

    public class Pair {
        private T first;
        private T second;
        public void setSecond(T newValue) {
            second = newValue;
        }
    }
    
    
    public class DateInterval extends Pair {
        public void setSecond(String second) {
            System.out.println("OK sub");
        }
    
        public static void main(String[] args) throws NoSuchFieldException, SecurityException {
            DateInterval interval = new DateInterval();
            Pair pair = interval;
            pair.setSecond("string1");
        }
    }
    

    Using the command javap -verbose DateInterval, you can see a bridge method:

    public void setSecond(java.lang.Object);
    flags: ACC_PUBLIC, ACC_BRIDGE, ACC_SYNTHETIC
    

    This was made up by compiler; it does not appear in your code.

提交回复
热议问题