Solved

Calling setters on abstract class

Posted on 2009-07-03
1
527 Views
Last Modified: 2013-11-24
Hi,

In my code I am instantiating an abstract class need to call the setters on that class. How can I call the setters on the class in a generic form without knowing the name of the setter.

Here is an example of what  I mean:


      Class clazz = Class.forName(getClassName());
      if (clazz!=null)
        Entity entity = (Entity)clazz.newInstance();

At runtime will know the name of the field I want to set, eg "Description". I know that there will be an associated setter named setDescription(String desc). But since I will not know this until runtimes I can't code this right now. Basically in pseudocode I would would do it like this for a field named "Description".

String fieldName = "Description";

Method method = "set" + fieldName;

entity."method"(value);

But how to do this ?

I'm guessing I should be able to do this using reflection but since I have no experience with reflection I'm not sure how to proceed.

Thanks for any advice.

Chris



0
Comment
Question by:ChrisOz2008
1 Comment
 
LVL 26

Accepted Solution

by:
ksivananth earned 500 total points
Comment Utility
Method[] methods = clazz.getMethods() will return all the methods

methods[0].getName() will give the name of the method, you can check if the name start with "set".

then invoke the method,

methods[0].invoke( entity, yourValue ) ;
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now