Meh*_*taş 7 c# java generics inheritance
我想编写C#代码的等效Java代码.
我的C#代码如下:
public abstract class A<T> where T : A<T>, new()
{
public static void Process()
{
Process(new T());
}
public static void Process(T t)
{
// Do Something...
}
}
public class B : A<B>
{
}
public class C : A<C>
{
}
Run Code Online (Sandbox Code Playgroud)
Java代码与我的代码相似.
public abstract class A<T extends A<T>>
{
public static <T extends A<T>> void process()
{
process(new T()); // Error: Cannot instantiate the type T
}
public static <T extends A<T>> void process(T t)
{
// Do Something...
}
public class B extends A<B>
{
}
public class C extends A<C>
{
}
}
Run Code Online (Sandbox Code Playgroud)
这里,类声明中的"new()"语法强制派生类编写一个默认的构造函数,这使得可以从基类调用"new T()".换句话说,当我在编写基类时,我确信派生类将具有默认的构造函数,以便我可以从基类实例化派生类对象.
我在Java中的问题是,我无法从超类中实例化派生类对象.我收到电话"Cannot instantiate the type T"错误"new T()".在Java中是否有类似的C#方式,或者我应该使用原型模式和克隆之类的东西?
Java不支持具体化的泛型,因此没有等效的" new T();".我解决这个问题的方法是对类型标记使用反射.类型标记指示泛型类型.
public abstract class A<T> {
private Class<T> typeToken;
// constructor
public A() {
typeToken = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用反射来实例化类.这很丑陋,但它完成了工作.