Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with Reflection

 
pjoisha
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic