如何解决Java 相当于 python 装饰器
在python中,您可以制作如下装饰器功能。注意:我从 https://www.ritchieng.com/python/decorators-kwargs-args/
复制并粘贴了此示例def printAllDecorator(func):
def inner(*args,**kwargs):
print ('Arguments for args: {}'.format(args))
print ('Arguments for kwargs: {}'.format(kwargs))
return func(*args,**kwargs)
return inner
@printAllDecorator
def multiply(a,b):
return a * b
>>> multiply(9,4)
Arguments for args: (9,4)
Arguments for kwargs: {}
36
Java 接口:
public interface MyInterface{
String helloWorld();
}
实现该接口的类,我希望能够对其进行装饰:
// package & imports...
public MyClasstoDecorate implements MyInterface {
@Override
String helloWorld(){
return "Hello World!";
}
}
public MyDecorator implements MyInterface {
private MyInterface myInterface;
public MyDecorator(MyClasstoDecorate myClasstoDecorate){
myInterface = myClasstoDecorate;
}
@Override
String helloWorld(){
return "From the decorator: " + myClasstoDecorate.helloWorld();
}
}
这一切都很好。但是...我的情况是我有 10 个不同的接口,每个接口都有 20 个或更多的功能,我想将这些功能中的每一个都包装在一个装饰器中。而装饰器对于它们中的每一个来说都是完全相同的代码。
如果您想知道我这样做是为了什么:我有一个 java spring 应用程序,我想模拟数据库故障。有 10 个不同的存储库接口。我想为每个存储库接口制作一个装饰器类,每个存储库接口都要求我覆盖至少 20 个函数。 10 个存储库 * 每个至少 20 个函数 = 至少 200 个函数,我必须一遍又一遍地编写相同的装饰器。
在python中,我的解决方案是只编写一次装饰器函数,如下所示:
# note: This isn't the exact logic I'm going to be using in my actual code.
# But this is a simple example to illustrate the kind of decorator I'm going for.
def someDecoratorFunction(func):
def wrapper(*args,**kwargs):
x = random.random()
if x < .80:
# forward request to actual repository
func(*args,**kwargs)
else:
# simulate database access failure
raise RuntimeError('Failed to open database')
return wrapper
然后我会创建 20 个新的装饰器类,每个类看起来像这样:
class ProxyEmployeeRepository(EmployeeRepositoryInterface):
def __init__(self,realFileRepository):
self.realFileRepository = realFileRepository
@someDecoratorFunction
def functionOne():
return self.realFileRepository.functionOne()
@someDecoratorFunction
def functionTwo();
return self.realFileRepository.functionTwo()
# do the same thing for all of the other functions...
这并不太乏味..是的,我需要制作 10 个类,每个类至少有 20 个函数,但至少我可以用一个简单的 @decoratorFunctionName
将装饰器包裹在每个函数周围。
有没有任何方法可以在java中做到这一点?还是 Java Spring?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。