Generic method in Java without generic argument

前端 未结 5 2079
无人共我
无人共我 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 14:05

    I am afraid what you are trying to do will simply not work in Java. Not being able to create new instances of generic types is one of those "must have" features that .NET provided while Java is simply missing. This leads to "workarounds" like those suggested earlier. Check out the ArrayList.toArray(T) as a reference how this can be done: essentially you will have to pass a reference to an object that you are trying to create so that you know what class to instantiate at runtime. This is the code from ArrayList.toArray(T):

    
    public  T[] toArray(T[] a)
    {
       if (a.length < size)
       {
          a = (T[]) java.lang.reflect.Array.
             newInstance(a.getClass().getComponentType(), size);
       }
       System.arraycopy(elementData, 0, a, 0, size);
       if (a.length > size)
       {
          a[size] = null;
       }
       return a;
    }
    
    

提交回复
热议问题