How to create a generic array in Java?

Due to the implementation of Java generics, you can’t have code like this: public class GenSet<E> { private E a[]; public GenSet() { a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation } } How can I implement this while maintaining type safety? I saw a solution on the Java forums that goes like this: … Read more

How do I use reflection to call a generic method?

What’s the best way to call a generic method when the type parameter isn’t known at compile time, but instead is obtained dynamically at runtime? Consider the following sample code – inside the Example() method, what’s the most concise way to invoke GenericMethod<T>() using the Type stored in the myType variable? public class Sample { … Read more

How to create a generic array in Java?

I have to ask a question in return: is your GenSet “checked” or “unchecked”? What does that mean? Checked: strong typing. GenSet knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E> argument, and methods will throw an exception when they are passed arguments that are not of type E. See Collections.checkedCollection.-> in that case, you should … Read more

Instantiating object of type parameter

After type erasure, all that is known about T is that it is some subclass of Object. You need to specify some factory to create instances of T. One approach could use a Supplier<T>: class MyClass<T> { private final Supplier<? extends T> ctor; private T field; MyClass(Supplier<? extends T> ctor) { this.ctor = Objects.requireNonNull(ctor); } public void myMethod() { field … Read more

Reflection generic get field value

Like answered before, you should use: Object value = field.get(objectInstance); Another way, which is sometimes prefered, is calling the getter dynamically. example code: public static Object runGetter(Field field, BaseValidationObject o) { // MZ: Find the correct method for (Method method : o.getMethods()) { if ((method.getName().startsWith(“get”)) && (method.getName().length() == (field.getName().length() + 3))) { if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase())) { … Read more