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
*/
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?