Generic method in Java without generic argument

前端 未结 5 2074
无人共我
无人共我 2020-12-02 13:32

In C# I can do actually this:

//This is C#
static T SomeMethod() where T:new()
{
  Console.WriteLine(\"Typeof T: \"+typeof(T));
  return new T();
}
         


        
5条回答
  •  庸人自扰
    2020-12-02 13:58

    Methods like Java's Collections.emptySet() have a signature like this:

    public static final  Set emptySet()
    

    And are called like this:

    Set foos = Collections.emptySet();
    

    Mockito's anyObject() method is another example. I personally don't find either syntax to be very awesome. Passing the type in as a method argument works but always felt kludgy. Providing the parameter in the way that emptySet() does seems cleaner but it's not always apparent that a method allows a type to be specified.

提交回复
热议问题