• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java reflection

 
Ranadhir Nag
Ranch Hand
Posts: 138
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to check a property in the javax.faces.component.html.HtmlInputText.
If i do it in the following manner,I get things fine:
if(comp.getClass().getName().equalsIgnoreCase("javax.faces.component.html.HtmlInputText")) {
String getter=((javax.faces.component.html.HtmlInputText)comp).getOnfocus();
if(getter!=null) {
System.out.println(getter);

}

}

But if i invoke it through reflection,I get nothing.
I am doing the following:
Class reqClass = Class.forName("javax.faces.component.html.HtmlInputText");
Method[] methodList = reqClass.getDeclaredMethods();
int methodIdx = 0;
for (int i = 0; i < methodList.length; i++) {
Method reqMethod =methodList[i];
if(reqMethod.getName().indexOf("getOn")== 0) //method starts with getOn
{

// method accepts parameters, define the types in order here as Class[]
Class[] classParams = new Class [] {};
// set the method of the class object
Method method = reqClass.getMethod( reqMethod.getName(), classParams );

// pass values to fill parameters of method
Object[] arguments = new Object [] {};
// invoke method via reflection.Note that class has default constructor
Object retobj=method.invoke( reqClass.newInstance() ,
arguments );

String getterResult = (String)retobj;

if(getterResult!=null)
{
System.out.println(reqMethod.getName() + " ## " + getterResult);
}
}
}

What am i doing wrong while invoking the method through reflection.
I get no exception either.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're doing pretty much OK until this line:

Object retobj=method.invoke( reqClass.newInstance() , arguments );

Remember that the whole point was to invoke a method on "comp", yes? But here, where you've identified the method, you create a new instance of the same class as "comp", and call the method on this new instance; presumably the new instance returns "null" from the method you're calling. Pass "comp" instead of "reqClass.newInstance()" here, and I think you'll be fine.
 
Ranadhir Nag
Ranch Hand
Posts: 138
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perfect.Thanks a lot
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic