Skip to content

Support Java record for v1.6. Fixes #1830 #1835

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 19, 2022
Merged
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 @@ -25,9 +25,7 @@
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.*;
import java.nio.charset.Charset;
import java.time.Duration;
import java.time.LocalTime;
Expand Down Expand Up @@ -175,17 +173,39 @@ private static Stream<MethodParameter> fromSimpleClass(Class<?> paramClass, Fiel
Annotation[] fieldAnnotations = field.getDeclaredAnnotations();
try {
Parameter parameter = field.getAnnotation(Parameter.class);
boolean isNotRequired = parameter == null || !parameter.required();
boolean isNotRequired = parameter == null || !parameter.required();
Annotation[] finalFieldAnnotations = fieldAnnotations;
return Stream.of(Introspector.getBeanInfo(paramClass).getPropertyDescriptors())
.filter(d -> d.getName().equals(field.getName()))
.map(PropertyDescriptor::getReadMethod)
.filter(Objects::nonNull)
.map(method -> new MethodParameter(method, -1))
.map(methodParameter -> DelegatingMethodParameter.changeContainingClass(methodParameter, paramClass))
.map(param -> new DelegatingMethodParameter(param, fieldNamePrefix + field.getName(), finalFieldAnnotations, true, isNotRequired));

if ("java.lang.Record".equals(paramClass.getSuperclass().getName())) {
Method classGetRecordComponents = Class.class.getMethod("getRecordComponents");
Object[] components = (Object[]) classGetRecordComponents.invoke(paramClass);

Class<?> c = Class.forName("java.lang.reflect.RecordComponent");
Method recordComponentGetAccessor = c.getMethod("getAccessor");

List<Method> methods = new ArrayList<>();
for (Object object : components) {
methods.add((Method) recordComponentGetAccessor.invoke(object));
}
return methods.stream()
.filter(method -> method.getName().equals(field.getName()))
.map(method -> new MethodParameter(method, -1))
.map(methodParameter -> DelegatingMethodParameter.changeContainingClass(methodParameter, paramClass))
.map(param -> new DelegatingMethodParameter(param, fieldNamePrefix + field.getName(), finalFieldAnnotations, true, isNotRequired));

}
else
return Stream.of(Introspector.getBeanInfo(paramClass).getPropertyDescriptors())
.filter(d -> d.getName().equals(field.getName()))
.map(PropertyDescriptor::getReadMethod)
.filter(Objects::nonNull)
.map(method -> new MethodParameter(method, -1))
.map(methodParameter -> DelegatingMethodParameter.changeContainingClass(methodParameter, paramClass))
.map(param -> new DelegatingMethodParameter(param, fieldNamePrefix + field.getName(), finalFieldAnnotations, true, isNotRequired));
}
catch (IntrospectionException e) {
catch (IntrospectionException | NoSuchMethodException |
InvocationTargetException | IllegalAccessException |
ClassNotFoundException e) {
return Stream.of();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
*
* *
* * *
* * * * Copyright 2019-2022 the original author or authors.
* * * *
* * * * 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
* * * *
* * * * https://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 org.springdoc.core;

import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.api.io.TempDir;

import org.springframework.core.MethodParameter;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Tests for {@link MethodParameterPojoExtractor}.
*/
class MethodParameterPojoExtractorTest {
@TempDir
File tempDir;

/**
* Tests for {@link MethodParameterPojoExtractor#extractFrom(Class<?>)}.
*/
@Nested
class extractFrom {
@Test
@EnabledForJreRange(min = JRE.JAVA_17)
void ifRecordObjectShouldGetField() throws IOException, ClassNotFoundException {
File recordObject = new File(tempDir, "RecordObject.java");
try (PrintWriter writer = new PrintWriter(new FileWriter(recordObject))) {
writer.println("public record RecordObject(String email, String firstName, String lastName){");
writer.println("}");
}
String[] args = {
recordObject.getAbsolutePath()
};
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int r = compiler.run(null, null, null, args);
if (r != 0) {
throw new IllegalStateException("Compilation failed");
}
URL[] urls = { tempDir.toURI().toURL() };
ClassLoader loader = URLClassLoader.newInstance(urls);

Class<?> clazz = loader.loadClass("RecordObject");

Stream<MethodParameter> actual = MethodParameterPojoExtractor.extractFrom(clazz);
assertThat(actual)
.extracting(MethodParameter::getMethod)
.extracting(Method::getName)
.containsOnlyOnce("email", "firstName", "lastName");
}

@Test
void ifClassObjectShouldGetMethod() {
Stream<MethodParameter> actual = MethodParameterPojoExtractor.extractFrom(ClassObject.class);
assertThat(actual)
.extracting(MethodParameter::getMethod)
.extracting(Method::getName)
.containsOnlyOnce("getEmail", "getFirstName", "getLastName");
}

public class ClassObject {
private String email;

private String firstName;

private String lastName;

public ClassObject(String email, String firstName, String lastName) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}
}
}
}