return new KeyGenerator() {
@Override
public Object generate(Object object, Method method, Object... objects) {
String username = null;
try {
username = objectStorageService.getAuthDetail().getUsername();
StringBuilder customisedkey = generateKey(object, method, objects);
customisedkey.append(username);
return customisedkey.toString();
} catch (BaseException e) {
LOGGER.error("Operation failed while generating Key", e);
return null;
}
}
};
SonarLint suggest me to "Make this anonymous inner class a lambda". but wasn't able to find a solution for this specific case
An anonymous inner class having just a single method can be converted in a lambda expression.
In particular this code:
return new KeyGenerator() {
@Override
public Object generate(Object object, Method method, Object... objects) {
String username = null;
try {
username = objectStorageService.getAuthDetail().getUsername();
StringBuilder customisedkey = generateKey(object, method, objects);
customisedkey.append(username);
return customisedkey.toString();
} catch (BaseException e) {
LOGGER.error("Operation failed while generating Key", e);
return null;
}
}
};
is equivalent to:
return (object, method, objects) -> {
String username = null;
try {
username = objectStorageService.getAuthDetail().getUsername();
StringBuilder customisedkey = generateKey(object, method, objects);
customisedkey.append(username);
return customisedkey.toString();
} catch (BaseException e) {
LOGGER.error("Operation failed while generating Key", e);
return null;
}
};
More in general a code similar to this one:
new MyClass() {
public ReturnType myUniqueMethod(ParameterType p) {
// body
}
}
can be replaced with
(p) -> {
// body
}
This operation can be generally executed automatically by modern IDE with a refactoring operation.