473,809 Members | 2,742 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem get the value of a field in the Reflection API

I have written a static method that uses the Reflection API to scrape
all of the names of the instance variables in a class and their
corresponding values; and then returns a hashMap containing a
key/value pair of the name of the variable and its corresponding
value. My problem is getting the value of the field, and everything I
have seen on usenet and in the javadoc tells me I am doing the right
thing. I think I found a bug in the JDK, but thought I'd throw it out
there to see if I am doing something wrong.

When I use the reflect API, specifically Field.get(Objec t o), it
returns the name of the variable, not the value contained in the
variable.

Note: The object (params) that I am passing in contains only primitive
types (double, int, etc.). I am using Java(TM) 2 Runtime Environment,
Standard Edition (build 1.4.2_03-b02).

Here is the code

public static HashMap toHash(Object params)
{
try
{
HashMap desc = new HashMap();
Class c = params.getClass ();
Field[] fields = c.getFields();
for (int i = 0; i < fields.length; i++)
{
String key = fields[i].getName(); //PROBLEM #1: field name is in
ALL CAPS
Object value = fields[i].get(params); //PROBLEM #2: returns the
name of the field, not it's value desc.put(key, value);
}
return desc;
}
catch (SecurityExcept ion e)
{
MiscUtils.write ("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERRO R_MESSAGE_TYPE) ;
e.printStackTra ce();
}
catch (IllegalArgumen tException e)
{
MiscUtils.write ("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERRO R_MESSAGE_TYPE) ;
e.printStackTra ce();
}
catch (IllegalAccessE xception e)
{
MiscUtils.write ("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERRO R_MESSAGE_TYPE) ;
e.printStackTra ce();
}
return null;
}

Any ideas?
Jul 17 '05 #1
3 10994
nos

"Richard" <rv********@von econsulting.com > wrote in message
news:d7******** *************** ***@posting.goo gle.com...
I have written a static method that uses the Reflection API to scrape
all of the names of the instance variables in a class and their
corresponding values; and then returns a hashMap containing a
key/value pair of the name of the variable and its corresponding
value. My problem is getting the value of the field, and everything I
have seen on usenet and in the javadoc tells me I am doing the right
thing. I think I found a bug in the JDK, but thought I'd throw it out
there to see if I am doing something wrong.

When I use the reflect API, specifically Field.get(Objec t o), it
returns the name of the variable, not the value contained in the
variable.

Note: The object (params) that I am passing in contains only primitive
types (double, int, etc.). I am using Java(TM) 2 Runtime Environment,
Standard Edition (build 1.4.2_03-b02).

Here is the code

public static HashMap toHash(Object params)
{
try
{
HashMap desc = new HashMap();
Class c = params.getClass ();
Field[] fields = c.getFields();
for (int i = 0; i < fields.length; i++)
{
String key = fields[i].getName(); //PROBLEM #1: field name is in
ALL CAPS
Object value = fields[i].get(params); //PROBLEM #2: returns the
name of the field, not it's value desc.put(key, value);
}
return desc;
}
catch (SecurityExcept ion e)
{
MiscUtils.write ("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERRO R_MESSAGE_TYPE) ;
e.printStackTra ce();
}
catch (IllegalArgumen tException e)
{
MiscUtils.write ("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERRO R_MESSAGE_TYPE) ;
e.printStackTra ce();
}
catch (IllegalAccessE xception e)
{
MiscUtils.write ("Unable to convert parameters to hash. " +
e.getMessage(), SystemInfo.ERRO R_MESSAGE_TYPE) ;
e.printStackTra ce();
}
return null;
}

Any ideas?

I do this (need to instantiate the object first)
then printout of the field name has the correct
upper/lower case. I did not try the value.
-----------------
CarlPlot cp = new CarlPlot(500, 500);
className = cp.getClass();

Field[] fields;
if (showall)
fields = cn.getFields();
else
fields = cn.getDeclaredF ields();
Jul 17 '05 #2
Nic
If you use javaBeans and javaBeanInfo you can make it.

//Istance of my bean class
Myclass istanceOfMyClas s = new MyClass();
//The Class of my class
Class classOfMyClass= Myclass.class;
//the BeanInfo: contains names and descriptions of the bean (if you
use Forte or NetBeans it's easy to do)
BeanInfo beanInfoOfMyCla ss =
Introspector.ge tBeanInfo(istan ceOfMyClass);
PropertyDescrip tor propertiesOfMyC lass[] =
beanInfoOfMyCla ss.getPropertyD escriptors();

for(int i=0;i<propertie sOfMyClass.leng th;i++){
Method getter = propertiesOfMyC lass[i].getReadMethod( );
Method setter = propertiesOfMyC lass[i].getWriteMethod ();
Object value = getter.invoke(i stanceOfMyClass , new Object[]{});
}

I hope I help you!

By.

Nic
Jul 17 '05 #3
oops. The original code works fine. I was making a stupid mistake.
Jul 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1344
by: Simang | last post by:
Hi everyone, I have a structure with this format: Public Structure Forms Public _01234 as string Public _04321 as string Public _03456 as integer End Structure As you can see, the variable names are all numeric. What I want to do
2
5882
by: Daniel | last post by:
Hello, i've created an old-ADO-recordset in C# via the following code: ADODB.RecordsetClass arTest; arTest = new ADODB.RecordsetClass(); arTest.Fields.Append("Field1",
4
1667
by: Nicolas | last post by:
The lat part is not working why ???????? Please help......... using System; namespace ConsoleApplication4 {
3
4415
by: dan | last post by:
Hi all, I have a reflection-problem I'm totally stuck with. Maybe someone has a hint... I want to get a fieldinformation of an event from the Control class, e.g. "TextChanged". FieldInfo fi = typeof(Control).GetField("TextChanged", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
1
24196
by: Mudassar | last post by:
i want to get the property value using reflection. Scenerio: i have a status bar on MDI form. it has property named "Panels" and i want to get a specific panel from that panels collection using reflection. Please let me know. Thanks C# Developer
5
6804
by: rettigcd | last post by:
I have several classes that all have the same static member: class A{ public static string Table = "TableA"; } class B{ public static string Table = "TableB"; }
8
1370
by: yo_mismo | last post by:
Hi, I send a parameter from a Form (Form1) to an other form (Form2): Form2 frm2 = new Form2(); frm2.number_frm2 = number_frm1; frm2.Show(); The problem i got is that the variable 'number_frm2' always have the value 0 (it's an integer). I have declared it as 'public' but i can't get the right
5
2386
by: Tomislav Bartolin | last post by:
Hi, Is it possible to set value to a read-only property via reflection? Thx -- Bartol -- Remove "TB" from address to reply
3
4104
by: Steve Amey | last post by:
Hi all I am using reflection to read the values of properties from a class. The class is returned from a Web Service so I have to access the class using FieldInfo (Using VS 2003 which converts the Properties into Fields when it comes out of the Web Service). I have this at the moment: Private _aDataSource As Object 'Person class
0
9601
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10379
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10115
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9199
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3014
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.