8000 Add ClassFile implementation for class metadata · spring-projects/spring-framework@4f260a4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 4f260a4

Browse files
committed
Add ClassFile implementation for class metadata
Prior to this commit, Spring Framework would allow two ways of getting class metadata: * `StandardClassMetadata`, using the Java reflection API * `SimpleMetadataReaderFactory`, using ASM to read the class bytecode This commit adds a new implementation for this feature, this time using the new `ClassFile` API which is taken out of preview in Java 24. See gh-33616
1 parent 28273b9 commit 4f260a4

File tree

11 files changed

+916
-7
lines changed

11 files changed

+916
-7
lines changed

spring-core/spring-core.gradle

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ apply plugin: "kotlin"
1111
apply plugin: "kotlinx-serialization"
1212

1313
multiRelease {
14-
targetVersions 17, 21
14+
targetVersions 17, 21, 24
1515
}
1616

1717
def javapoetVersion = "1.13.0"
@@ -25,6 +25,10 @@ configurations {
2525
graalvm
2626
}
2727

28+
springFramework {
29+
enableJavaPreviewFeatures = true
30+
}
31+
2832
task javapoetRepackJar(type: ShadowJar) {
2933
archiveBaseName = 'spring-javapoet-repack'
3034
archiveVersion = javapoetVersion

spring-core/src/main/java/org/springframework/core/type/classreading/MetadataReaderFactory.java

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -19,12 +19,15 @@
1919
import java.io.IOException;
2020

2121
import org.springframework.core.io.Resource;
22+
import org.springframework.core.io.ResourceLoader;
23+
import org.springframework.lang.Nullable;
2224

2325
/**
2426
* Factory interface for {@link MetadataReader} instances.
2527
* Allows for caching a MetadataReader per original resource.
2628
*
2729
* @author Juergen Hoeller
30+
* @author Brian Clozel
2831
* @since 2.5
2932
* @see SimpleMetadataReaderFactory
3033
* @see CachingMetadataReaderFactory
@@ -49,4 +52,23 @@ public interface MetadataReaderFactory {
4952
*/
5053
MetadataReader getMetadataReader(Resource resource) throws IOException;
5154

55+
/**
56+
* Create a default {@link MetadataReaderFactory} implementation that's suitable
57+
* for the current JVM.
58+
* @return a new factory instance
59+
* @since 7.0
60+
*/
61+
static MetadataReaderFactory create(@Nullable ResourceLoader resourceLoader) {
62+
return MetadataReaderFactoryDelegate.create(resourceLoader);
63+
}
64+
65+
/**
66+
* Create a default {@link MetadataReaderFactory} implementation that's suitable
67+
* for the current JVM.
68+
* @return a new factory instance
69+
* @since 7.0
70+
*/
71+
static MetadataReaderFactory create(@Nullable ClassLoader classLoader) {
72+
return MetadataReaderFactoryDelegate.create(classLoader);
73+
}
5274
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.core.type.classreading;
18+
19+
import org.springframework.core.io.ResourceLoader;
20+
import org.springframework.lang.Nullable;
21+
22+
/**
23+
* Internal delegate for instantiating {@link MetadataReaderFactory} implementations.
24+
* For JDK < 24, the {@link SimpleMetadataReaderFactory} is being used.
25+
*
26+
* @author Brian Clozel
27+
* @since 7.0
28+
* @see MetadataReaderFactory
29+
*/
30+
abstract class MetadataReaderFactoryDelegate {
31+
32+
static MetadataReaderFactory create(@Nullable ResourceLoader resourceLoader) {
33+
return new SimpleMetadataReaderFactory(resourceLoader);
34+
}
35+
36+
static MetadataReaderFactory create(@Nullable ClassLoader classLoader) {
37+
return new SimpleMetadataReaderFactory(classLoader);
38+
}
39+
}
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.core.type.classreading;
18+
19+
20+
import java.lang.classfile.Annotation;
21+
import java.lang.classfile.AnnotationElement;
22+
import java.lang.classfile.AnnotationValue;
23+
import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute;
24+
import java.lang.reflect.Array;
25+
import java.util.ArrayList;
26+
import java.util.Collections;
27+
import java.util.LinkedHashMap;
28+
import java.util.LinkedHashSet;
29+
import java.util.List;
30+
import java.util.Map;
31+
import java.util.Set;
32+
33+
import org.springframework.core.annotation.AnnotationFilter;
34+
import org.springframework.core.annotation.MergedAnnotation;
35+
import org.springframework.core.annotation.MergedAnnotations;
36+
import org.springframework.lang.Nullable;
37+
import org.springframework.util.ClassUtils;
38+
39+
abstract class ClassFileAnnotationMetadata {
40+
41+
static MergedAnnotations createMergedAnnotations(String entryName, RuntimeVisibleAnnotationsAttribute annotationAttribute, @Nullable ClassLoader classLoader) {
42+
Set<MergedAnnotation<?>> annotations = new LinkedHashSet<>(4);
43+
annotationAttribute.annotations().forEach(ann -> {
44+
MergedAnnotation<java.lang.annotation.Annotation> mergedAnnotation = createMergedAnnotation(entryName, ann, classLoader);
45+
if (mergedAnnotation != null) {
46+
annotations.add(mergedAnnotation);
47+
}
48+
});
49+
return MergedAnnotations.of(annotations);
50+
}
51+
52+
@SuppressWarnings("unchecked")
53+
@Nullable
54+
private static <A extends java.lang.annotation.Annotation> MergedAnnotation<A> createMergedAnnotation(String entryName, Annotation annotation, @Nullable ClassLoader classLoader) {
55+
String typeName = fromTypeDescriptor(annotation.className().stringValue());
56+
if (AnnotationFilter.PLAIN.matches(typeName)) {
57+
return null;
58+
}
59+
Map<String, Object> attributes = new LinkedHashMap<>(4);
60+
try {
61+
Class<A> annotationType = (Class<A>) ClassUtils.forName(typeName, classLoader);
62+
for (AnnotationElement element : annotation.elements()) {
63+
attributes.put(element.name().stringValue(), readAnnotationValue(element.value(), classLoader));
64+
}
65+
Map<String, Object> compactedAttributes = (attributes.isEmpty() ? Collections.emptyMap() : attributes);
66+
return MergedAnnotation.of(classLoader, new Source(entryName), annotationType, compactedAttributes);
67+
}
68+
catch (ClassNotFoundException | LinkageError ex) {
69+
return null;
70+
}
71+
}
72+
73+
private static Object readAnnotationValue(AnnotationValue elementValue, @Nullable ClassLoader classLoader) throws ClassNotFoundException {
74+
switch (elementValue) {
75+
case AnnotationValue.OfArray arrayValue -> {
76+
List<AnnotationValue> rawValues = arrayValue.values();
77+
List<Object> values = new ArrayList<>(rawValues.size());
78+
for (AnnotationValue arrayEntry : rawValues) {
79+
values.add(readAnnotationValue(arrayEntry, classLoader));
80+
}
81+
Class<?> elementType = getArrayElementType(values);
82+
return values.toArray((Object[]) Array.newInstance(elementType, rawValues.size()));
83+
}
84+
case AnnotationValue.OfAnnotation annotationValue -> {
85+
return annotationValue.annotation();
86+
}
87+
case AnnotationValue.OfClass classValue -> {
88+
return fromTypeDescriptor(classValue.className().stringValue());
89+
}
90+
case AnnotationValue.OfEnum enumValue -> {
91+
return parseEnum(enumValue, classLoader);
92+
}
93+
case AnnotationValue.OfConstant constantValue -> {
94+
return constantValue.resolvedValue();
95+
}
96+
default -> {
97+
return elementValue;
98+
}
99+
}
100+
}
101+
102+
private static Class<?> getArrayElementType(List<Object> values) {
103+
if (values.isEmpty()) {
104+
return Object.class;
105+
}
106+
Object firstElement = values.getFirst();
107+
if (firstElement instanceof Enum<?> enumeration) {
108+
return enumeration.getDeclaringClass();
109+
}
110+
return firstElement.getClass();
111+
}
112+
113+
private static String fromTypeDescriptor(String descriptor) {
114+
return descriptor.substring(1, descriptor.length() - 1)
115+
.replace('/', '.');
116+
}
117+
118+
@SuppressWarnings("unchecked")
119+
private static <E extends Enum<E>> Enum<E> parseEnum(AnnotationValue.OfEnum enumValue, @Nullable ClassLoader classLoader) throws ClassNotFoundException {
120+
String enumClassName = fromTypeDescriptor(enumValue.className().stringValue());
121+
Class<E> enumClass = (Class<E>) ClassUtils.forName(enumClassName, classLoader);
122+
return Enum.valueOf(enumClass, enumValue.constantName().stringValue());
123+
}
124+
125+
record Source(String entryName) {
126+
127+
}
128+
129+
}

0 commit comments

Comments
 (0)
0