It's possible to use reflection with a generic type?
For example:
// MyClass.java
import java.lang.reflect.*;
public class MyClass<E> {
public MyClass() {
Method[] methods = <E>.getClass().getMethods();
for (int i = 0; i < methods.length; ++i)
System.out.println(methods[i].getName());
}
}
// Test.java
public class Test {
public void methodA() {}
public void methodB() {}
public void methodC() {}
public static void main(String[] args) {
new MyClass<Test>();
}
}
This will print all methods from class Test. Basically, I need only
obtain the Class object that represents the class passed to the generic
argument E of the class MyClass
P.Hill - 09 May 2006 03:09 GMT
> It's possible to use reflection with a generic type?
>...
> Basically, I need only
> obtain the Class object that represents the class passed to the generic
> argument E of the class MyClass
A little reading in the API doc should help.
What have you tried?
-Paul
Magno Machado - 09 May 2006 03:18 GMT
>A little reading in the API doc should help.
I can't find anything that should help me. :(
> What have you tried?
I tried some forms, but without results. The maximum that obtained was
to get the names of the generic parameters (the E in the example that I
gave).
P.Hill - 09 May 2006 05:11 GMT
>>A little reading in the API doc should help.
>
[quoted text clipped - 5 lines]
> to get the names of the generic parameters (the E in the example that I
> gave).
But isn't that what you asked for?
If you only have a class name then isn't the class not far away using
Class.forName(String s)?
Also, since the code you gave doens't compile for me, what is the right
code?
-Paul
Chris Uppal - 09 May 2006 10:26 GMT
> It's possible to use reflection with a generic type?
No, not in the way you are trying to do it. The nearest (as far as I know)
that you can get is something like:
============
import java.lang.reflect.*;
class MyClass<E>
{
public MyClass(Class<E> c)
{
for (Method method : c.getMethods())
System.out.println(method.getName());
}
}
public class Test
{
public void methodA() {}
public void methodB() {}
public void methodC() {}
public static void
main(String[] args)
{
new MyClass<Test>(Test.class);
}
}
============
You can use a helper method to remove some of the repetition, e.g:
============
public class Test2
{
public void methodA() {}
public void methodB() {}
public void methodC() {}
public static void
main(String[] args)
{
helper(Test2.class);
}
static <X> MyClass<X>
helper(Class<X> c)
{
return new MyClass<X>(c);
}
}
============
But the idea is the same either way. You have to find the class object in a
non-generic context and pass that to the generic code (indeed the code which
uses it may not need to be generic at all, which would also remove the need for
repetition).
-- chris