문제

I have a class that is consisted of the following primitive types only:

public class Test{

private int a1; //size of int =4
private long a2; //size of long = 8
private double a3[]; //size of double =8

}

Moreover, I have an object for this class like this:

Test test= new Test(1,3,new double[] {0.1, 0.2, 0.3, 0.4});

I would like to have a function that will find the size of this object and in this case it would return 4 + 8 + 4*8 = 44.

도움이 되었습니까?

해결책

If I am understanding the question correctly, then it is something you could have easily implemented yourself, but here we go:

public class Test {
    private int a1;
    private long a2;
    private double a3[];

    public Test(final int a1, final long a2, final double[] a3) {
        this.a1 = a1;
        this.a2 = a2;
        this.a3 = a3;
    }

    public int getSize() {
        return 4 + 8 + (a3.length * 8);
    }
}

Also a few notes:

  • Refrain from using Test as classname, you should use something like SizeTest or whatever, but simply test will eventually cause havoc if you would decide to unit test it or whatnot.
  • Give variables meaningful names. If I had the oppurtunity I would've done so, but I can really cannot make anything from the current names.

If you are looking for a generic function, then well things turn a lot harder, in that case you would be looking for a method with the followed signature: SizeTester.getSize(Object object);, it is still doable, but you would need to use Reflection then to get information about the fields and you should only use that if absolutely neccessary.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top