Java is strongly typed. If an annotation expects a value of one type (e.g., Day.MONDAY
of enum type Day
), and due to external modification or corrupted metadata, it receives something else (e.g., java.lang.String
), the JVM throws AnnotationTypeMismatchException
.
This exception is rare in normal Java code. It usually happens when:
- Bytecode is altered by tools (e.g., ASM, Javassist).
- Annotations are loaded from corrupted class files.
- External libraries create annotations dynamically with invalid values.
Program Demonstration using Dynamic Proxy
Since this exception cannot be triggered in normal source code (compiler prevents it), we’ll simulate it using Java reflection and dynamic proxies.
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Priority {
Level value(); // Expects enum type
}
enum Level {
HIGH, MEDIUM, LOW;
}
Code language: PHP (php)
Proper Usage
@Priority(Level.HIGH)
class SafeTask {
}
Code language: JavaScript (javascript)
Simulated Runtime Mismatch via Proxy
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.lang.annotation.AnnotationTypeMismatchException;
public class AnnotationTypeMismatchDemo {
public static void main(String[] args) {
try {
// Simulate a malformed annotation using Proxy
Priority corrupted = (Priority) Proxy.newProxyInstance(
Priority.class.getClassLoader(),
new Class[]{Priority.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("annotationType")) {
return Priority.class;
}
// Simulate returning a String where an Enum is expected
throw new AnnotationTypeMismatchException(method, "INVALID_VALUE");
}
}
);
// This triggers the exception
System.out.println("Value: " + corrupted.value());
} catch (AnnotationTypeMismatchException e) {
System.out.println("Caught AnnotationTypeMismatchException");
System.out.println("Method with mismatch: " + e.element());
System.out.println("Mismatched value: " + e.foundType());
}
}
}
Code language: JavaScript (javascript)
Expected Output
Caught AnnotationTypeMismatchException
Method with mismatch: public abstract Level Priority.value()
Mismatched value: INVALID_VALUE
Code language: PHP (php)
AnnotationTypeMismatchException
is a rare but important runtime exception that alerts developers when annotation values do not match the expected type.It generally occurs in reflection-based or dynamically proxied environments, especially when annotation metadata is corrupt or manipulated.Simulating this exception requires careful crafting of proxies and exceptions, as Java’s type system prevents this during normal compilation.Best practices include avoiding bytecode tampering, using default values carefully, and validating annotation metadata before relying on it.