jaykataria1111 commented on issue #2769:
URL:
https://github.com/apache/logging-log4j2/issues/2769#issuecomment-2456586762
So my original idea was something of this sorts, This would be during the
build of the field, which would be **runtime**
In Plugin Builder.java
```
for (final ConstraintValidator<?> validator : validators) {
if (!validator.isValid(field, builder)) {
if (!reason.isEmpty()) {
reason += ", ";
}
if (validator instanceof PublicSetterValidator) {
reason += "field '" + field.getName() + " does not
have a public setter";
} else {
reason += "field '" + field.getName() + "' has
invalid value '" + value + "'";
}
}
}
}
return reason;
```
Implementing a constraint Validator, and changing the interface.
```
public interface ConstraintValidator<A extends Annotation> {
...
/**
* Indicates if the given value is valid.
*
* @param name the name to use for error reporting
* @param value the value to validate.
* @return {@code true} if the given value is valid.
*/
default boolean isValid(String name, Object value) {
return true;
}
default boolean isValid(Field field, final Builder<?> builder) throws
IllegalAccessException {
final Object value = field.get(builder);
return isValid(field.getName(), value);
}
}
```
```
public class PublicSetterValidator implements
ConstraintValidator<PluginBuilderAttribute> {
private static final Logger LOGGER = StatusLogger.getLogger();
private PluginBuilderAttribute annotation;
/**
* @param annotation the annotation value this validator will be
validating.
*/
@Override
public void initialize(PluginBuilderAttribute annotation) {
this.annotation = annotation;
}
@Override
public boolean isValid(Field field, Builder<?> builder) {
Class<?> declaringClass = field.getDeclaringClass();
Class<?> fieldType = field.getType();
Method[] methods = declaringClass.getMethods();
for (Method method : methods) {
if
(method.getName().toLowerCase(Locale.ROOT).contains(field.getName().toLowerCase(Locale.ROOT))
&&
method.getName().toLowerCase(Locale.ROOT).startsWith("set")
&& method.getParameterCount() == 1
&& method.getParameterTypes()[0].equals(fieldType)
&&
java.lang.reflect.Modifier.isPublic(method.getModifiers())) {
return true; // Found a valid public setter according to
convention.
}
}
return false; // Could not find a method with a valid public setter.
}
}
```
I do see this has a lots of flaws though already for that purpose, and its
too drastic
Doing it at compile time makes more sense. Thanks a lot for giving me a
direction on this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]