Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

import com.vaadin.flow.function.ValueProvider;
import com.vaadin.flow.internal.BeanUtil;
import com.vaadin.flow.internal.ReflectTools;

/**
* A {@link PropertySet} that uses reflection to find bean properties.
Expand Down Expand Up @@ -550,6 +551,12 @@ private static boolean hasNonObjectReadMethod(

private static Object invokeWrapExceptions(Method method, Object target,
Object... parameters) {
// canAccess() rejects a null target; invoke() then throws the
// NullPointerException callers expect for a broken property chain
if (target != null && !method.canAccess(target)) {
// the bean type does not need to be public
ReflectTools.makeAccessible(method);
}
try {
return method.invoke(target, parameters);
} catch (IllegalAccessException | InvocationTargetException e) {
Expand Down
10 changes: 8 additions & 2 deletions flow-data/src/main/java/com/vaadin/flow/data/binder/Binder.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.vaadin.flow.data.binder;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.RecordComponent;
Expand Down Expand Up @@ -3088,9 +3089,14 @@ public BEAN writeRecord() throws ValidationException {
final List<Object> convertedValues = new ArrayList<>();
values.forEach(value -> value.ifOk(convertedValues::add));

Constructor<?> constructor = beanType.getDeclaredConstructors()[0];
if (!constructor.canAccess(null)) {
// the record type does not need to be public
ReflectTools.makeAccessible(constructor);
}
try {
record = beanType.cast(beanType.getDeclaredConstructors()[0]
.newInstance(convertedValues.toArray()));
record = beanType.cast(
constructor.newInstance(convertedValues.toArray()));
} catch (Exception e) {
throw ReflectTools.convertInstantiationException(e, beanType);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
Expand All @@ -41,6 +42,7 @@
import com.vaadin.flow.tests.data.bean.Address;
import com.vaadin.flow.tests.data.bean.Country;
import com.vaadin.flow.tests.data.bean.FatherAndSon;
import com.vaadin.flow.tests.data.bean.NonPublicBeans;
import com.vaadin.flow.tests.data.bean.Sex;
import com.vaadin.flow.tests.server.ClassesSerializableUtils;

Expand Down Expand Up @@ -550,4 +552,44 @@ void includesDefaultMethodsFromInterfaces() {
assertEquals(String.class, defs.get(3).getType());

}

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
void nonPublicBeanClass_getterAndSetterWork() {
Object bean = NonPublicBeans.newBeanWithChild();
PropertySet<Object> set = BeanPropertySet
.get((Class) NonPublicBeans.BEAN_TYPE);

PropertyDefinition<Object, Object> name = (PropertyDefinition) set
.getProperty("name").get();
name.getSetter().get().accept(bean, "parent");
assertEquals("parent", name.getGetter().apply(bean));

PropertyDefinition<Object, Object> childName = (PropertyDefinition) set
.getProperty("child.name").get();
childName.getSetter().get().accept(bean, "child");
assertEquals("child", childName.getGetter().apply(bean));
assertEquals("parent", name.getGetter().apply(bean));
}

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
void beanClassInPackageNotOpened_getterFailsWithHint() {
// the JDK's Path implementation lives in a package that is neither
// exported nor opened, so its accessors cannot be made accessible
Path bean = Path.of("file.txt");
PropertySet<Object> set = BeanPropertySet.get((Class) bean.getClass());
ValueProvider<Object, ?> getter = set.getProperty("fileName").get()
.getGetter();

IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class, () -> getter.apply(bean));
String message = exception.getMessage();
assertTrue(message.contains("'getFileName'"), message);
assertTrue(message.contains(bean.getClass().getName()), message);
assertTrue(message.contains(
"open the package '" + bean.getClass().getPackageName() + "'"),
message);
assertTrue(message.contains("module-info.java"), message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import com.vaadin.flow.data.validator.NotEmptyValidator;
import com.vaadin.flow.data.validator.StringLengthValidator;
import com.vaadin.flow.internal.CurrentInstance;
import com.vaadin.flow.tests.data.bean.NonPublicBeans;
import com.vaadin.flow.tests.data.bean.Person;
import com.vaadin.flow.tests.data.bean.Sex;

Expand Down Expand Up @@ -2975,6 +2976,21 @@ void readRecord_writeRecord() throws ValidationException {
assertThrows(ValidationException.class, () -> binder.writeRecord());
}

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
void readRecord_writeRecord_nonPublicRecord() throws ValidationException {
Binder<Object> binder = new Binder<>(
(Class) NonPublicBeans.RECORD_TYPE);
TestTextField nameField = new TestTextField();
binder.forField(nameField).bind("name");

binder.readBean(NonPublicBeans.newRecord("test"));
assertEquals("test", nameField.getValue());

nameField.setValue("foo");
assertEquals(NonPublicBeans.newRecord("foo"), binder.writeRecord());
}

private TestTextField createNullRejectingFieldWithEmptyValue(
String emptyValue) {
return new TestTextField() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2000-2026 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.tests.data.bean;

/**
* Bean types that are not public, declared outside the binder package so that
* reflective access from the binder classes is checked against the class
* visibility.
*/
public final class NonPublicBeans {

public static final Class<?> BEAN_TYPE = Bean.class;

public static final Class<?> RECORD_TYPE = Record.class;

private NonPublicBeans() {
}

public static Object newBeanWithChild() {
Bean bean = new Bean();
bean.setChild(new Bean());
return bean;
}

public static Object newRecord(String name) {
return new Record(name);
}

static class Bean {
private String name;
private Bean child;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Bean getChild() {
return child;
}

public void setChild(Bean child) {
this.child = child;
}
}

record Record(String name) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
Expand Down Expand Up @@ -71,6 +72,7 @@ public class ReflectTools implements Serializable {
static final String CREATE_INSTANCE_FAILED_CONSTRUCTOR_THREW_EXCEPTION = "Unable to create an instance of '%s'. The constructor threw an exception.";
static final String CREATE_INSTANCE_FAILED_NO_NON_PRIVATE_NOARG_CONSTRUCTOR = "Unable to create an instance of '%s'. Make sure the class has a no-arg constructor that is not private.";
static final String CREATE_INSTANCE_FAILED_INACCESSIBLE_CONSTRUCTOR = "Unable to create an instance of '%s'. Its module does not open the package '%s' to Vaadin. Make the class and its no-arg constructor public, or open the package in module-info.java.";
static final String ACCESS_FAILED_PACKAGE_NOT_OPEN = "Unable to access %s of '%s'. Its module does not open the package '%s' to Vaadin. Make the class public, or open the package in module-info.java.";

private static final Predicate<Method> IS_SYNTHETIC = Method::isSynthetic;

Expand Down Expand Up @@ -626,6 +628,32 @@ public static <T> T createInstanceWithAccessibleConstructor(Class<T> cls) {
}
}

/**
* Makes the given method or constructor accessible, so that it can be
* invoked even when its declaring class is not public, for example a data
* class nested in a view.
*
* @param member
* the method or constructor to make accessible
* @throws IllegalArgumentException
* if the member cannot be made accessible because the package
* of its declaring class is in a named module that does not
* open it to Vaadin
*/
// S3011: making non-public members accessible is the purpose of the method
@SuppressWarnings("java:S3011")
public static void makeAccessible(Executable member) {
if (!member.trySetAccessible()) {
Class<?> type = member.getDeclaringClass();
String memberName = member instanceof Constructor
? "the constructor"
: String.format("'%s'", member.getName());
throw new IllegalArgumentException(
String.format(ACCESS_FAILED_PACKAGE_NOT_OPEN, memberName,
type.getName(), type.getPackageName()));
}
}

/**
* Creates an instance of the given {@code proxyClass} with no-arg
* constructor.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
Expand Down Expand Up @@ -234,6 +235,22 @@ void createInstanceWithAccessibleConstructor_packageNotOpen_descriptiveError()
cls.getName(), cls.getPackageName()), exception.getMessage());
}

@Test
void makeAccessible_packageNotOpen_descriptiveError()
throws ClassNotFoundException {
// A JDK class whose package java.base neither exports nor opens
Class<?> cls = Class.forName("sun.nio.cs.UTF_8");
Constructor<?> constructor = cls.getDeclaredConstructors()[0];

IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> ReflectTools.makeAccessible(constructor));
assertEquals(
String.format(ReflectTools.ACCESS_FAILED_PACKAGE_NOT_OPEN,
"the constructor", cls.getName(), cls.getPackageName()),
exception.getMessage());
}

@Test
void createInstanceWithAccessibleConstructor_privateConstructor_rejected() {
IllegalArgumentException exception = assertThrows(
Expand Down
Loading