开发者

Java. How to prohibit usage of raw generic type?

开发者 https://www.devze.com 2023-01-22 08:19 出处:网络
Hi I\'m writing the reporting system and want to make end-user specify type if he extends my class. class A <T extends C>

Hi I'm writing the reporting system and want to make end-user specify type if he extends my class.

class A <T extends C>
{...}

class B extends A /开发者_JS百科/ Compile error
{...}

class B extends A<D> // Compile error
{...}

class B extends A<C> // Success

Is that possible?


class B extends A // Compile error

No, for the sake of backwards compatibility, generics in Java are optional. You cannot force the programmer to use them. This will only generate a warning ("do not use raw types").

 class B extends A<D>  // compile error

If they do use generics, they have to be correct, though. In the case that D does not match the specification, this will be a compiler error.


@Thilo is right.

I'd just like to add that it is a bad idea to try to force people to use your classes in a particular way. They may have a good reason for using your code differently to the way that you intend. If you try to force a particular usage pattern, you may end up causing people to resort to horrible hacks, to fork your classes, or to simply go away and implement their own.


This is a job for your IDE or for external quality management tools (like Findbugs). You can configure Eclipse to treat unchecked warnings as error (and you can probably do the same with most IDEs). Or you can configure Findbugs to make your build fail in the same type of error.

Yes, those solutions leave the responsability to the user of your API to do the right thing, but it is most probably the right thing to do.

0

精彩评论

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

关注公众号