diff --git a/src/main/java/org/apache/bcel/classfile/RecordComponentInfo.java b/src/main/java/org/apache/bcel/classfile/RecordComponentInfo.java index 2aabce87e2..4a1c349aa0 100644 --- a/src/main/java/org/apache/bcel/classfile/RecordComponentInfo.java +++ b/src/main/java/org/apache/bcel/classfile/RecordComponentInfo.java @@ -77,6 +77,25 @@ public void dump(final DataOutputStream file) throws IOException { } } + /** + * Gets the attribute for the given tag if present, or null if absent. + * + * @param the attribute type. + * @param tag the attribute tag. + * @return Attribute for given tag, null if not found. + * Refer to {@link org.apache.bcel.Const#ATTR_UNKNOWN} constants named ATTR_* for possible values. + * @since 6.13.0 + */ + @SuppressWarnings("unchecked") + public final T getAttribute(final byte tag) { + for (final Attribute attribute : getAttributes()) { + if (attribute.getTag() == tag) { + return (T) attribute; + } + } + return null; + } + /** * Gets all attributes. * diff --git a/src/test/java/org/apache/bcel/classfile/RecordTest.java b/src/test/java/org/apache/bcel/classfile/RecordTest.java index 9588e4e761..afdd7fe32e 100644 --- a/src/test/java/org/apache/bcel/classfile/RecordTest.java +++ b/src/test/java/org/apache/bcel/classfile/RecordTest.java @@ -21,12 +21,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import org.apache.bcel.AbstractTest; +import org.apache.bcel.Const; import org.apache.bcel.util.SyntheticRepository; import org.apache.bcel.visitors.CountingVisitor; import org.junit.jupiter.api.Test; @@ -118,4 +120,14 @@ void testRecordToString() throws ClassNotFoundException, ClassFormatException, I assertEquals("RecordComponentInfo(aNumber,I,0):", firstComponent.toString()); } + @Test + void testRecordComponentGetAttribute() throws ClassFormatException, IOException { + final JavaClass clazz = new ClassParser("src/test/resources/record/SimpleRecord.class").parse(); + final Record recordAttribute = (Record) findAttribute("Record", clazz)[0]; + final RecordComponentInfo secondComponent = recordAttribute.getComponents()[1]; + final RuntimeVisibleAnnotations ann = secondComponent.getAttribute(Const.ATTR_RUNTIME_VISIBLE_ANNOTATIONS); + assertEquals("RuntimeVisibleAnnotations:\n" + + " @Ljavax/annotation/Nonnull;", ann.toString()); + assertNull(secondComponent.getAttribute(Const.ATTR_RUNTIME_INVISIBLE_ANNOTATIONS)); + } }