开发者

Java: allowed to add custom class to java.awt.image?

I'm pretty shure the answer is somewhere, but either im lacking the correct key-words or simply should get some sleep, but here it is ;~) :

I need to extend BufferedImage and the only way to do this w/o MacGyvering the whole class would be to let the new class rest in java.awt.image, because it contains a package-visible-only field i need to access. Normaly, there would be a reason to dont to such a thing, but if you check the source, you'll see that this is not true in this special case.

So I tested it, it compiles and it seems to run.

But can i rely on it? Is it allowed? Is there anything that could prevent me from adding classes to java's predefined system packages? Or is this simply the correct way to do it and no one told me?

UPDATE

The answeres already provided stated the possibility of legal concerns (if doing something correctly means breaking some laws than my default solution frequently is beeing uninterested in those laws;-) and the possibility of changed behaviour in the super-class (very unlikely in that case). If that's all, i'd just do it that way…

UPDATE2

Great! Java is a protected package name… So i really have to MacGyver this…

UPDATE3

I was just wondering why i cant get the property hash-keys. The fn getPropertyNames is documented just so: Returns an array of names recognized by getProperty(String)… let's look into the sourcecode:

public String[] getPropertyNames() {
     return null;
}

Best code i'v开发者_JS百科e ever read…


Ok, here's how I would handle this:

public class MyBi extends BufferedImage
{
    private final BufferedImage realBufferedImage;

    public MyBi(BufferedImage bi)
    {
        super(0, 0, TYPE_INT_ARGB);
        realBufferedImage = bi;
    }

    // Add methods for managing your extra data

    // For every method in BufferedImage, override it like so:
    public void setData(Raster r)
    {
        realBufferedImage.setData(r);
    }
}

This is tedious to do by hand, but NetBeans has support for delegating. Press Alt Insert, select Delegate Method..., select realBufferedImage as the field in the left panel, check BufferedImage in the right panel and click OK. Instant delegation.

This should work because, although the fields of BufferedImage are at package scope, nothing else in the package accesses them.


You don't "add" to java.awt.Image. In your own package you extend the class and do as you please.

Sometimes, in open source projects, you can submit your class back to the project and have it become part of the project.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜