简体   繁体   English

Java默认方法 - 获取子类的类型

[英]Java Default Method - get type of subclass

I have an interface in which I want to provide a default method to Serialize the inherited classes. 我有一个接口,我想在其中提供一个默认方法来序列化继承的类。 I use a JsonSerializer<T> class to do serialization. 我使用JsonSerializer<T>类来进行序列化。

The method looks like: 该方法如下:

public interface A
{
    public default String write()
    {
        new JsonSerializer</*Inherited class type*/>();
        // I've tried new JsonSerializer<this.getClass()>();  - Doesn't work

    }
}

public class AX implements A
{
}

So when I instantiate AX, I want to use the write method to serialize AX 因此,当我实例化AX时,我想使用write方法来序列化AX

AX inst = new AX();
String instSerialized = inst.write();

I need to pass the type of AX to the write method in A. is this possible? 我需要将AX的类型传递给A中的write方法。这可能吗?

I believe what you might be looking for is an interface declaration like this: 我相信你可能正在寻找的是这样的接口声明:

public interface A<T extends A<T>>
{
    public default String write()
    {
        new JsonSerializer<T>();
    }
}

public class AX implements A<AX>
{
}

Using Self-bounding generics is sometimes useful, when you need to reference the current class as a generic argument. 当您需要将当前类作为泛型参数引用时,使用自定义泛型有时很有用。 This is eg also done by the java Enum class: abstract class Enum<E extends Enum<E>> . 这也是由例如java Enum类完成的: abstract class Enum<E extends Enum<E>>

The type parameters in the generics mechanism are a compile-time information, only. 泛型机制中的类型参数仅是编译时信息。 This type information is erased in the bytecode. 该类型信息在字节码中被擦除。

The exact class type of an object (which you can retrieve with getClass() ) is a runtime information. 对象的确切类类型(可以使用getClass()检索)是运行时信息。

The conclusion: As you can only put static type names inside the generics brackets, there is no way to make any runtime calls there. 结论:由于您只能将静态类型名称放在泛型括号中,因此无法在那里进行任何运行时调用。

The only way to make your serializer somewhat covariant is to write 使序列化程序有点协变的唯一方法是编写

new JsonSerializer<? extends A>() ...

But the real question should be: What yre you trying to achieve? 但真正的问题应该是:你想要实现什么? I feel, that your approach does not solve your problem. 我觉得,你的方法并不能解决你的问题。

Use generics in the interface 在界面中使用泛型

public interface A<T> {

    public default String write() {
        new JsonSerializer<T>();
        // I've tried new JsonSerializer<this.getClass()>();  - Doesn't work
    }
}

public class AX implements A<AX> {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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