It's not a secret anymore!
The moose likes Java in General and the fly likes Not being successful 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 "Not being successful with Reflection" Watch "Not being successful with Reflection" New topic

Not being successful with Reflection

Yogendra Joshi
Ranch Hand

Joined: Apr 04, 2006
Posts: 213
Hi folks ,

I have been trying my hands with reflection today.. and bored with this error

What i am trying to acheive is , I have a class in which i get the name of other class using Class.forName("ReflectionTest") like this :

Class Yogs=Class.forName("ReflectionTest");

then i make an instance of this class by referring to Object class like this :

Object NewInst = Yogs.newInstance();

Then in the try section , I try to Locate a String field named hello using Field class , but when i run the code , it gives the above NoSuchFieldException , Can all of you experts highlight , where i am going wrong , below are the 2 java files which i have used for the above.

Please help in this new learning of mine.
Thanks in advance.

Yogendra N Joshi

Meri Zindagi Hain Tab Tak.. Jab Tak Tera Sahara.... Har Taraf Tu Hi Tu Hain SAI Tera Hi Hain Nazara.....
Nitesh Kant

Joined: Feb 25, 2007
Posts: 1638

The code works fine except for the fact that your class ReflectionTest does not compile as in the for loop you have not declared the variable i.
After fixing the above problem, the program runs fine.
Probably you have an earlier version of the class ReflectionTest that does not have the field Hello.

apigee, a better way to API!
Daniel Chemko
Ranch Hand

Joined: Feb 27, 2008
Posts: 32
Java fields are case sensitive:

private String field = "lowerCase";
private String Field = "firstUpperCase";
private String FIELD = "allUpperCase";

getClass().getField("field").get(this) == "lowerCase"
getClass().getField("Field").get(this) == "firstUpperCase"
getClass().getField("FIELD").get(this) == "allUpperCase"
Yogendra Joshi
Ranch Hand

Joined: Apr 04, 2006
Posts: 213
Hi Nitesh / Daniel ,

A great thanks for your wonderful help. I have been able to get the type now. It works fine.

Thanks a lot

Yogendra N Joshi.
I agree. Here's the link:
subject: Not being successful with Reflection
jQuery in Action, 3rd edition