22

I'm trying to understand Java reflecton and am encountering difficulties when working with non-Integer setter methods.

As an example, how can I resolve the "getDeclaredMethod()" call below?

import java.lang.reflect.*;

class Target {
    String value;

    public Target() { this.value = new String("."); }
    public void setValue(String value) { this.value = value; }
    public String getValue() { return this.value; }
}

class ReflectionTest {
    public static void main(String args[]) {
        try {
            Class myTarget = Class.forName("Target");

            Method myMethod;
            myMethod = myTarget.getDeclaredMethod("getValue");  // Works!
            System.out.println("Method Name: " + myMethod.toString());

            Class params[] = new Class[1];
            //params[0] = String.TYPE; // ?? What is the appropriate Class TYPE?
            myMethod = myTarget.getDeclaredMethod("setValue", params); // ? Help ?
            System.out.println("Method Name: " + myMethod.toString());

        } catch (Exception e) {
            System.out.println("ERROR");
        }
    }
}
2
  • One Question I have for you, in what scenario, I will try to know which methods are in the class and Variables? why I will try to know that? I am exploring the reasons for using this methods getDeclaredMethod(), getDeclaredFields() , etc... Can you please suggest Commented Mar 2, 2010 at 11:08
  • One (random) reason for using reflection is if you want to build a Json serialization/deserialization library. The well known Google Gson library heavily use reflections to achieve his tasks. Examples of such usages can continue forever. You can for example build a network protocol you can use to serialize and send various Java objects properties to another application or to a server based on another language saving a huge amount of time for not having to implement a serialize method for all the classes you want exchange. Commented Nov 22, 2017 at 0:04

1 Answer 1

24
params[0] = String.class;

Using class on String will return the Class<?> that is associated with the String class.

Sign up to request clarification or add additional context in comments.

2 Comments

(Oops, I didn't mean to upvote the comment!) I just wanted to add that I wasn't aware of it to the other day, so it's not exactly that obvious.
One Question I have for you, in what scenario, I will try to know which methods are in the class and Variables? why I will try to know that? I am exploring the reasons for using this methods getDeclaredMethod(), getDeclaredFields() , etc... Can you please suggest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.