my dog learned polymorphism*
The moose likes Java in General and the fly likes Java reflection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java reflection" Watch "Java reflection" New topic
Author

Java reflection

Ranadhir Nag
Ranch Hand

Joined: Mar 09, 2006
Posts: 138
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Ranadhir Nag
Ranch Hand

Joined: Mar 09, 2006
Posts: 138
Perfect.Thanks a lot
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Java reflection