aspose file tools*
The moose likes Java in General and the fly likes Problem with Reflection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem with Reflection" Watch "Problem with Reflection" New topic
Author

Problem with Reflection

pjoisha
Ranch Hand

Joined: Mar 06, 2001
Posts: 123
Hi all,
I have run into a situation wherein for some reason sample 2 code
(show below) does not work via reflection:
// I have this wrapper object defined ....
public class Info
{
private String info;
public Info() {}
public Info(String data) {
info = data;
}
}
// Sample 1
Info[] inf = new Info[1];
inf[1] = new Info("Hello");

// Sample 2 (via reflection):
Class arrayClass = Class.forName("Info");
// This fails ..returns null
Class componentClass = arrayClass.getComponentType();
// And hence creation fails
Object result = Array.newInstance(componentClass, 1);
// I have left out Array.set ...

Why does this fail (I kinda see from the API for Class
that this will return an array class if one is passed
into forName method - This leads me to another question
what is this array class the docs are alluding to?)
How could I fix sample 2 code to achieve sample 1?
TIA,
PJ
Aj Manch
Ranch Hand

Joined: May 07, 2001
Posts: 50
Info[] inf = new Info[1];
inf[1] = new Info("Hello");

This should give an ArrayIndexOutOfBoundsException.

Class componentClass = arrayClass.getComponentType();
// And hence creation fails

You get null here because you are dealing with Info Class not an Info[] Class.
HTH,
AJ
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with Reflection