简体   繁体   English

Java:从ByteBuffer扩展

[英]Java : Extending from ByteBuffer

Java will not allow me to extend from ByteBuffer because it implements abstract methods that I am not overriding, yet these methods work for any ByteBuffer objects that are created, such as asDoubleBuffer()... Java不允许我从ByteBuffer扩展,因为它实现了我不重写的抽象方法,但是这些方法适用于所创建的任何ByteBuffer对象,例如asDoubleBuffer()...

byte[] bytes = new byte[256];
ByteBuffer buf = ByteBuffer.wrap(bytes);
DoubleBuffer db = buf.asDoubleBuffer();

Yet, if I extend a new class from ByteBuffer, it forces me to implement asDoubleBuffer(), even though the superclass already implements this method, obviously, since I can call it just fine. 但是,如果我从ByteBuffer扩展了一个新类,那么即使超类已经实现了此方法,显然它也迫使我实现asDoubleBuffer(),因为我可以很好地调用它。 I'm totally not understanding what's going on here... Please explain this to me. 我完全不了解这里发生了什么...请向我解释一下。

The ByteBuffer factory method returns a class which implements ByteBuffer. ByteBuffer工厂方法返回一个实现ByteBuffer的类。

byte[] bytes = new byte[256];
ByteBuffer buf = ByteBuffer.wrap(bytes);
System.out.println(buf.getClass());

prints 版画

class java.nio.HeapByteBuffer

Using ByteBuffer is a relatively advanced tool, you need to understand Java pretty well before you try to extend it IMHO. 使用ByteBuffer是一个相对高级的工具,在尝试扩展IMHO之前,您需要非常了解Java。


You can see this by looking at the code. 您可以通过查看代码来查看。 In my IDE you can find it by doing a <shift>+<click> on the method. 在我的IDE中,可以通过对方法执行<shift> + <click>来找到它。

public static ByteBuffer wrap(byte[] array) {
    return wrap(array, 0, array.length);
}

calls 电话

public static ByteBuffer wrap(byte[] array,
                                int offset, int length)
{
    try {
        return new HeapByteBuffer(array, offset, length);
    } catch (IllegalArgumentException x) {
        throw new IndexOutOfBoundsException();
    }
}

BTW: I am a big fan of using ByteBuffer, however you really need to understand what you are doing to use it. 顺便说一句:我是使用ByteBuffer的忠实拥护者,但是您确实需要了解使用它的方式。 esp when parsing data from a ByteBuffer. 尤其是从ByteBuffer解析数据时。 Developers with ten years experience find it tricky to use. 具有十年经验的开发人员发现使用起来很棘手。

Nevermind. 没关系。 I see that when a new ByteBuffer is allocated it returns a subclass that uses those abstract methods. 我看到分配新的ByteBuffer时,它将返回使用这些抽象方法的子类。 The object created is not really a ByteBuffer at all. 创建的对象实际上根本不是ByteBuffer。 Confusing to me. 让我困惑。 Not sure why they would use this methodology. 不知道为什么他们会使用这种方法。

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

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