FAQ

Java

JSP

Servlet


Advertisement



How to Use Reflection to Access Fields of a Class in Java?

The following example shows how to get and set fields' value in a class:

Tweedle.java,

package com.xyzws;
public enum Tweedle {
DEE, DUM
}

Book.java,

package com.xyzws;

public class Book {

private long chapters = 0;
protected String[] characters = { "Alice", "White Rabbit" };
public Tweedle twin = Tweedle.DEE;

public long getChapters() {
return chapters;
}
public void setChapters(long chapters) {
this.chapters = chapters;
}
public String[] getCharacters() {
return characters;
}
public void setCharacters(String[] characters) {
this.characters = characters;
}
public Tweedle getTwin() {
return twin;
}
public void setTwin(Tweedle twin) {
this.twin = twin;
}

}

and Program.java

package com.xyzws;

import java.lang.reflect.Field;
import java.util.Arrays;
import static java.lang.System.out;

public class Program {

public static void main(String... args) {
Book book = new Book();
String fmt = "%6S: %-12s = %s%n";

try {
Class c = book.getClass();

Field chap = c.getDeclaredField("chapters");
chap.setAccessible(true);
out.format(fmt, "before", "chapters",
chap.getLong(book));
chap.setLong(book, 12);
out.format(fmt, "after", "chapters",
chap.getLong(book));

Field chars = c.getDeclaredField("characters");
out.format(fmt, "before", "characters",
Arrays.asList((String[])chars.get(book)));
String[] newChars = { "Queen", "King" };
chars.set(book, newChars);
out.format(fmt, "after", "characters",
Arrays.asList((String[])chars.get(book)));

Field t = c.getDeclaredField("twin");
out.format(fmt, "before", "twin", t.get(book));
t.set(book, Tweedle.DUM);
out.format(fmt, "after", "twin", t.get(book));

} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}

/*
BEFORE: chapters = 0
AFTER: chapters = 12
BEFORE: characters = [Alice, White Rabbit]
AFTER: characters = [Queen, King]
BEFORE: twin = DEE
AFTER: twin = DUM
*/


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |