方面j。在多个类中创建内部类型方法
如果我输入:
public CountryState CountryState.find(long id) {
return (CountryState) findById(CountryState.class, id);
}
我正在类 CountryState 中创建一个 find 方法。
有没有办法在多个类中创建一个方法?我需要为每个要创建的类重复代码吗?
我知道,通过方面,我可以使一个类从另一个类继承,但是,这样做,我可以创建一个超类,因为 java 不接受多重继承。
If I put:
public CountryState CountryState.find(long id) {
return (CountryState) findById(CountryState.class, id);
}
I'm creating a method find in the class CountryState.
Is there a way to create a method in several classes? Do I need to repeat the code for each class I want to create?
I know that with aspect I can make a class inherit from another, but, doing this, I can create one superclass because java doesn't accept multiple inheritance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个“模式”就是您在 AspectJ 中执行此操作的方式。
声明接口:
在接口上进行类型间声明:
当您在接口上进行类似的声明时,您将提供“默认实现”。因此,该接口现在将定义 getMeAnInt() ,并且任何未实现 getMeAnInt() 的 Holder 实现都将获得默认实现。
难题的最后一部分是使用声明父级来指定哪组类型实现您的接口:
因此现在,任何用 @Anno 注释的类型都将实现 Holder 并具有 getMeAnInt() 方法。
This 'pattern' is how you do it in AspectJ.
Declare an interface:
Make your intertype declarations on the interface:
When you make a declaration like that on an interface you are providing a 'default implementation'. So the interface will now define getMeAnInt() and any implementations of Holder that do not implement getMeAnInt() will get the default implementation.
The final piece of the puzzle is then to use declare parents to specify which group of types implement your interface:
So now, any type annotated with @Anno will implement Holder and have the getMeAnInt() method.
其实不使用AOP也可以解决这个问题。你可以只使用 OOP/OOD。有两种方法(我假设您想编写一次方法):
使用方法实现创建抽象基类并从中派生所有类。实际上,这不是最好的主意。
创建帮助器类来实现您的 find() 方法并在类之间共享它(使用依赖注入,或者只是通过紧密耦合它们)。
因此,如果我理解正确的话,您实际上想要的是一个将返回目标类实例的通用方法:
You can actually solve it without using AOP. You could just use OOP/OOD. There are two ways (I assume you want to write method once):
Create abstract base class with the method implementation and derive all classes from it. This not the best idea, actually.
Creating helper class that will implement your find() method and share it between classes (either using Dependency Injection, or just by coupling them tightly).
So if I understand it correctly, what you want actually is a generic method that will return instances of the target class: