1

I only play with Java for fun, my background is mostly C++, so my question might seem a little strange for professional Java developers.

Say we have a Bitmap class filled with some pixels we want to read. Of course, the first best solution is getPixel method, but it makes some unnecessary checks for every pixel and thus works a bit slow. We could of use getPixels, but it copies the bitmap data doubling it in size and there is not too much spare memory on our target device. Not to mention, copying still takes time.

Is there some way to get objects field in Java omitting the interface?

akalenuk
  • 3,815
  • 4
  • 34
  • 56
  • 1
    The only thing that springs to mind is to use `Reflections`, but that is probably more inefficient than using the accessor method. – christopher Jun 01 '13 at 10:02
  • 2
    The only way to break encapsulation of classes whose code you don't own is reflection. – Marko Topolnik Jun 01 '13 at 10:11
  • Actually, this might work! I just have to get a reference to pixels once. This operation itself could be slow, but I would save a lot more processor time while processing thousands of pixels. – akalenuk Jun 01 '13 at 10:13

1 Answers1

3

Java offers a handy instrument for writing dynamic programs called Reflection. The closest thing to it in C++ is RTTI, but reflection is a lot more sophisticated. Among other things, it lets you access private fields of objects.

Suppose the third-party Bitmap looks like this:

class Bitmap {
    private byte[] rawData;
    private int rows;
    private int cols;
    public int getPixel(int x, int y) {
        if (x < 0 || x >= cols || y < 0 || y >= rows) {
            throw new ...
        }
        int offset = 3*(rows*y + x);
        return (rawData[offset] << 16)
             | (rawData[offset+1] << 8)
             | rawData[offset+2];
    }
}

Let's say that you want to avoid going through the getPixel method for each pixel by accessing rawData directly, but the field is not public. You can examine the Bitmap class for its private fields through reflection, get its rawData field by name, and access the array through reflection as if it were public.

It is needless to say that this approach is extremely fragile, especially when you use it with third-party libraries.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523