I have a method fetchObjects(String)that should return an array of business objects Contract. The parameter classNametells me which business objects I should return (of course, this does not make sense in this interpreted case, because I already said that I would return Contracts, but this is basically the situation that I have in my real scenario). So I get a record set somewhere and load a collection record class (whose type is specified className).
Now I need to build an array to return, so I use the method Set toArray(T[]). Using reflection, I create myself an empty array of Contracts. But that gives me a static type value Object! So next time I will need to apply it to the corresponding type, which in this case is equal Contract[](see the "asterisk-underlined" section in the list below).
My question is: is there a way and how to do for Contract[]as I do in the listing, but determining the type of the elements of the array ( Contract) only through className(or entriesType)? In other words, I would like to do this: (entriesType[]) valueWithStaticTypeObjectwhere entriesType will be replaced by the class specified with the parameter className, i.e. Contract.
Is this somehow intrinsically impossible, or can it be done somehow? Can generics be used?
package xx.testcode;
import java.util.HashSet;
import java.util.Set;
class TypedArrayReflection {
public static void main(String[] args) {
try {
Contract[] contracts = fetchObjects("Contract");
System.out.println(contracts.length);
} catch (ClassNotFoundException e) {}
}
static Contract[] fetchObjects(String className) throws ClassNotFoundException {
Class<?> entriesType = Class.forName("xx.testcode."+className);
Set<?> entries = ObjectManager.getEntrySet(className);
return entries.toArray(
(Contract[]) java.lang.reflect.Array.newInstance(
entriesType, entries.size()) );
}
}
class Contract { }
class ObjectManager {
static Set<?> getEntrySet(String className) {
if (className.equals("Contract"))
return new HashSet<Contract>();
return null;
}
}
Thanks.
Update: Using a safe type toArraytaken from CodeIdol , I updated minefetchObjects this way:static Contract[] fetchObjects(String className) throws ClassNotFoundException {
Class<?> entriesType = Class.forName("xx.testcode."+className);
Set<?> entries = ObjectManager.getEntrySet(className);
return toArray(entries, entriesType);
}
public static <T> T[] toArray(Collection<T> c, Class<T> k) {
T[] a = (T[]) java.lang.reflect.Array.newInstance(k, c.size());
int i = 0;
for (T x : c)
a[i++] = x;
return a;
}
What do I need to do to get rid of the compiler error mentioned in the comment? Should I definitely indicate Set<Contract>in the return type of my method getEntrySetso that this can work? Thanks for any pointers.
source
share