简体   繁体   中英

Is it possible to instantiate an object of generic type in Java or C#?

For example, in Java, if I have a parameterized class, is it possible to do the following?

public class MyClass<T>{
  public void aMethod {
    ..
    T object = new T();
    ..
  }
  ..
}

In Java, I think it is not possible, because the compiler doesn't know what constructor to call. But in C#? I don't know the language and I've read that many dark things can be done, so I was just wondering..

this is possible in C# if you are setting constraint on T type to have parameterless constructor.

public class MyClass<T> where T:new(){
   public void aMethod {
   ..
   T object = new T();
   ..
   }
   ..

}

See here .

Like Donut said, C# allows you to instantiate arbitrary types at runtime using Activator.CreateInstance which works a bit like Class<?>.newInstance in Java. Since C#'s Generics are preserved after compilation, C#, unlike Java, allows you to get hold of a Type instance for a given type parameter and thus call CreateInstance or any other constructor.

For the parameterless constructor, this is considerably easier, using a generic constraint:

void <T> T createT() where T : new()
{
    return new T();
}

The key here is where T : new() .

In the general case, using reflection, you can use the following:

void <T> T createT()
{
    var typeOfT = typeof(T);
    return (T) Activator.CreateInstance(typeOfT, new object[] { arg1, arg2 … });
}

Yes, it's possible. You can use Activator.CreateInstance<T>();

From MSDN :

Activator.CreateInstance(T) Method
Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor.

In c# you can use the where keyword

private class MyClass<T> where T : new()
{
        private void AMethod()
        {
            T myVariable = new T();
        }
}

You can do this in Java via reflection:

public class Example {
    public static void main(String[] args) throws Exception {
        String s = create(String.class);
    }

    // Method that creates a new T
    public static <T> T create(Class<T> c) throws InstantiationException, IllegalAccessException {
        return c.newInstance();
    }
}

Java中不太丑陋的变通方法之一: Javassist

To summarize, in java there is no way to instantiate a generic type T. In C#, there are several ways.

Am I understanding this correctly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM