Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a generic map using type given at runtime

The title may be a bit hard to understand, but let me just briefly describe my problem.

Let's assume I have an annotation like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Identifier {

}

Now, I make a class which annotates any of its fields with it:

public class Student {
    private String name;
    private String surname;
    @Identifier
    private String idNumber;
    ...
}

Finally, at runtime I want to create a Map with the key type of typeof(field annotated with @Identifier) and the value type of Student. Note that any field can be annotated with @Identifier.

Any ideas?

EDIT

Ok, let me clarify this a bit:

class Student {
    private String name;
    private String surname;
    @Identifier
    private String idNumber;
}

class Foo {
    @Identifier
    private Integer x;
}

//  Now, what I want to have are two maps:

SortedMap students;     //  key type: String
                        //  value type: Student
SortedMap foos;         //  key type: Integer
                        //  value type: Foo

Thanks in advance!

like image 893
Pateman Avatar asked Aug 01 '26 06:08

Pateman


1 Answers

I'm still not exactly sure what you want to do.

at runtime I want to create a Map with the key type of typeof(field annotated with @Identifier) and the value type of Student

You can create a raw Map or a Map<Object, Object>. You can get the type of the field annotated with @Identifier. I'm not sure what you mean by value type of Student so I'll assume you mean the type Student, ie. its Class object.

public static void main(String[] args) throws Exception {
    Class<?> clazz = Student.class;
    Map<Object, Object> map = new HashMap<>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        Identifier annotation = field.getAnnotation(Identifier.class);
        if (annotation != null) {
            map.put(field.getType(), clazz);
        }
    }
    System.out.println(map);
}

With your example class in your question, this prints

{class java.lang.String=class com.spring.Student}

So the annotated field type is mapped to the class type.

You won't be able to have a Map<String,Student> though because you don't know the type String (and possibly not even Student) at compile time. You can try casting, but you're setting yourself up for a number of ClassCastExceptions.

like image 111
Sotirios Delimanolis Avatar answered Aug 02 '26 20:08

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!