How do you provide a default type for generics?

后端 未结 6 1574
醉梦人生
醉梦人生 2020-12-30 18:58

I have a class that currently has several methods that take integer parameters. These integers map to operations that the application can perform. I\'d like to make the clas

6条回答
  •  情深已故
    2020-12-30 19:42

    The compiler can infer the type arguments on fields most of the time based on the type of the arguments passed:

    import lombok.Data;
    
    @Data
    public class MyClass {
    
        private T myField;
    }
    

    can be used as,

    MyClass myClass = new MyClass();
    String abc = "hello world !";
    myClass.setMyField(abc);
    System.out.println("test generic class with generic field = " + myGenericClass.getMyField());
    

    and that should result into,

    test generic class with generic field = hello world !
    

提交回复
热议问题