• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Reflection  RSS feed

 
Suman Chaudhuri
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I have a class as such :

<pre>
public class Employee {

private String name;
private Address address;
private Collection phones;

//getter and setters for above fields go here

}

public class Address {

private String address1;

//getter and setter for address1
}

public class Phone {

private String number;

//getter and setter for number

}


</pre>

I want to write some reflection code, that given a field name, will drill down to the appropriate class, find the field and set it to "".

For example, say the reflection code class name is DataFilter and it has a "filter" method. Then calling :

a) DataFilter.filter(this, "name") will set the Employee.name = ""

b) DataFilter.filter(this, "Address.address1") will first know that I need to extract the field whose datatype is Address, then look for the "address1" field in Address and set it to ""

c) DataFilter.filter(this, Phone.number) will go thru Employee, and once it cant find a field whose datatype is "Phone", will then look to see if there are any collections, and, in this case, when it finds one, will iterate thru the collection and if there are any objects of type "Phone", will set all the "number" fields of that collection of Phone objects to ""

I am new to Java and this is a bit complex for me. Can someone please help me out ? If someone can show me how to write this, I would really be grateful.

Thank you so much for your time. I really appreciate it.
 
Judd Smith
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the process to follow:
From the object, get a Class object
Using that object, get a list of methods available
Find the method you want to call from that list
Assemble the required arguments into a list of objects
Call the method, an object is returned

Here's an example ...
 
Max Habibi
town drunk
( and author)
Sheriff
Posts: 4118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

There aren't many rules around here, but we have one. Please change your display name to comply with The JavaRanch Naming Policy.

Thanks,
M
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should definitely check out the jakarta commons beanutils. They have already written many helper classes to perform such functionality including traversing nested properties, e.g. address.address1. In particular, look at the api docs for BeanUtils, PropertyUtils, and MethodUtils.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!