Stop generating unnecessary reference to field type

This commit updates the generator to stop specifying a field type when
reflection is necessary, or when a reference to a field should be
retrieved as its name alone suffices.

This could trigger package protected issues if the field type is not
public.

See gh-28047
This commit is contained in:
Stephane Nicoll
2022-03-08 15:43:29 +01:00
parent e873715737
commit 9809752c3c
5 changed files with 22 additions and 24 deletions

View File

@@ -224,7 +224,7 @@ public class InjectionGenerator {
CodeBlock generateFieldInjection(Field injectionPoint, boolean required) {
Builder code = CodeBlock.builder();
code.add("instanceContext.field($S, $T.class", injectionPoint.getName(), injectionPoint.getType());
code.add("instanceContext.field($S", injectionPoint.getName());
code.add(")\n").indent().indent();
if (required) {
code.add(".invoke(beanFactory, (attributes) ->");
@@ -236,8 +236,8 @@ public class InjectionGenerator {
if (hasAssignment) {
code.beginControlFlow("");
String fieldName = String.format("%sField", injectionPoint.getName());
code.addStatement("$T $L = $T.findField($T.class, $S, $T.class)", Field.class, fieldName, ReflectionUtils.class,
injectionPoint.getDeclaringClass(), injectionPoint.getName(), injectionPoint.getType());
code.addStatement("$T $L = $T.findField($T.class, $S)", Field.class, fieldName, ReflectionUtils.class,
injectionPoint.getDeclaringClass(), injectionPoint.getName());
code.addStatement("$T.makeAccessible($L)", ReflectionUtils.class, fieldName);
code.addStatement("$T.setField($L, bean, attributes.get(0))", ReflectionUtils.class, fieldName);
code.unindent().add("}");

View File

@@ -298,11 +298,10 @@ public final class BeanDefinitionRegistrar {
/**
* Create an {@link InjectedElementResolver} for the specified field.
* @param name the name of the field
* @param type the type of the field
* @return a resolved for the specified field
*/
public InjectedElementResolver field(String name, Class<?> type) {
return new InjectedFieldResolver(getField(name, type), this.beanName);
public InjectedElementResolver field(String name) {
return new InjectedFieldResolver(getField(name), this.beanName);
}
/**
@@ -315,9 +314,9 @@ public final class BeanDefinitionRegistrar {
return new InjectedMethodResolver(getMethod(this.beanType, name, parameterTypes), this.beanType, this.beanName);
}
private Field getField(String fieldName, Class<?> fieldType) {
Field field = ReflectionUtils.findField(this.beanType, fieldName, fieldType);
Assert.notNull(field, () -> "No field '" + fieldName + "' with type " + fieldType.getName() + " found on " + this.beanType);
private Field getField(String fieldName) {
Field field = ReflectionUtils.findField(this.beanType, fieldName);
Assert.notNull(field, () -> "No field '" + fieldName + "' found on " + this.beanType.getName());
return field;
}