开发者

Forcing to use a class from another package with the same name of a class in the current package

since you guys helped me out, I stumbled upon a strange 'issue' while programming Java.

I'm programming in the Play framework. It uses a lot of equally named classes among a number of packages. It makes your code look pretty, but I encountered a rather nasty side-effect:

I have a class 'User' in my controller package. But of course, 'User' is also a model. While I'm writing in another controller, I need to create a new User object.

User u = User.find(...);

Because the controller User hasn't got such a method, this fails.

Am I correct if the only way to solve this is to write

models.users.User u = models.users.User.find(...);

After a little discu开发者_JS百科ssion with a Scala enthusiast, it seems that Java has no support to fix this kind of issues. Or is he wrong?

Kind regards


If I understand your question correct, if you do:

import models.users.User;

you will have access to the object without the full package. That's assuming you don't need the controller and the model in the same class.

If you need both, then yes, you have to fully qualify (add the package) one of them.

That said, it's a good convention to name all controllers XXXXController (or something like that). More generally, your own code should not have 2 different classes with the same name. The reason is that makes code readability lower, as User in one place behaves in a way and in some other piece of code behaves in a different way.

So the best solution would be to rename your controller.


He is right. You don't have any other way out of this.

It makes your code look pretty

I wouldn't say that. It makes my code convoluted and insanely difficult to comprehend.


You are correct. If you need to use both the User in your controller and the User class in the framework in the same class, then you can import one and then use the full package name for the other.

This can get confusing of course and I would reccomend one of two things:

1) one rename your class to something else. 2) do not import either and use the full package name for both. That way when reading the code it is less confusing.

I reccomend option 1.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜