Java 三元语句断开构造函数

Java 三元语句断开构造函数,java,android,eclipse,Java,Android,Eclipse,我正在为Eclipse中的android项目编写一个顶点类,在构造函数中我遇到了一个运行时错误。这是构造器 public Vertices(GLGraphics glGraphics, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords) { this.glGraphics = glGraphics; this.hasColor = hasColor; this.hasTexCoo

我正在为Eclipse中的android项目编写一个顶点类,在构造函数中我遇到了一个运行时错误。这是构造器

public Vertices(GLGraphics glGraphics, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords)
{
    this.glGraphics = glGraphics;
    this.hasColor = hasColor;
    this.hasTexCoords = hasTexCoords;
    this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;

    ByteBuffer buffer = ByteBuffer.allocateDirect(maxVertices * vertexSize);
    buffer.order(ByteOrder.nativeOrder());
    vertices = buffer.asFloatBuffer();

    if(maxIndices > 0)
    {
        buffer = ByteBuffer.allocateDirect(maxIndices * Short.SIZE / 8);
        buffer.order(ByteOrder.nativeOrder());
        indices = buffer.asShortBuffer();
    }
    else
    {
        indices = null;
    }
}
在本声明中:

this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;

我正在计算顶点的大小(以字节为单位)。问题是,每当计算三元运算时,vertexSize保持为0,程序在该语句处中断构造函数。三元运算符不会根据条件是真是假来计算其值。这里发生了什么?

您遇到了空指针异常。三值运算符的第一个操作数不能为
null

当您运行此行时,
hasColor
必须以null形式输入,这会导致程序出现运行时错误。这将导致程序结束,并且永远不会分配
vertexSize

this.vertexSize=(2+(hasColor?4:0)+(hasTexCoords?2:0))*4

检查你的日志,它会告诉你情况就是这样

编辑


正如@jahroy提到的,虽然它会在这一行抛出一个NPE,但当它传递到构造函数中时,它可能实际上抛出了NPE。如果您试图将
null
强制转换为布尔值,您还将得到一个NPE。

部分问题是您试图在一行代码中执行太多操作。我强烈建议你休息一下

this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;
分为三行代码:

int colorWeight = hasColor ? 4 : 0;
int texCoordWeight = hasTexCoords ? 2 : 0;

this vertexSize = (2 + colorWeight + texCoordWeight) * 4

注意这是多么容易阅读。此外,当您收到错误消息时,更容易找到原因。

如何爆发?有logcat消息吗?在调试器中跳过它做什么?你可能是对的,但是NPE会在构造函数执行之前抛出(当一个空布尔对象试图将自己转换为作为参数传递的基本布尔值时)。伙计们,它是一个小b布尔值,而不是大b布尔值,它不能为空,因为在他使用它时,hasColor将是传入的对象,因为它屏蔽了类级别1。@Kaediil我相信他们正在考虑布尔对象自动为传入的参数值解除绑定的可能性。如果布尔参数在函数调用之前为空,这将导致NPE。@Kaediil-同意。这就是为什么我指出,如果是NPE情况,那么NPE将在构造函数执行之前抛出(当尝试将空布尔值转换为原始布尔值时)。当然,我们假设错误是NPE。当OP发布任何错误日志时,我们可以确认这一点。