You can use:

String value = (String) this.getClass().getDeclaredField("str").get(this);

Or in a more generalized and safer form:

Field field = anObject.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
String value = (String) field.get(anObject);

And for your example, this should be enough:

String value = this.str; 

But you probably know of that one.

Note: anObject.getClass().getDeclaredField() is potentially unsafe as anObject.getClass() will return the actual class of anObject. See this example:

Object anObject = "Some string";
Class<?> clazz = anObject.getClass();
System.out.println(clazz);

Will print:

class java.lang.String

And not:

class java.lang.Object

So for your code's safety (and to avoid nasty errors when your code grows), you should use the actual class of the object you're trying to extract the field from:

Field field = YourObject.class.getDeclaredField(fieldName);
Answer from Lino on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › reflect › member › fieldValues.html
Getting and Setting Field Values (The Java™ Tutorials > The Reflection API > Members)
Because such access usually violates the design intentions of the class, it should be used with the utmost discretion. The Book class illustrates how to set the values for long, array, and enum field types. Methods for getting and setting other primitive types are described in Field. import java.lang.reflect.Field; import java.util.Arrays; import static java.lang.System.out; enum Tweedle { DEE, DUM } public class Book { public long chapters = 0; public String[] characters = { "Alice", "White Rabbit" }; public Tweedle twin = Tweedle.DEE; public static void main(String...
Discussions

java - Reflection generic get field value - Stack Overflow
I am trying to obtain a field's value via reflection. The problem is I don't know the field's type and have to decide it while getting the value. This code results with this exception: Can not set... More on stackoverflow.com
🌐 stackoverflow.com
What’s the point of Java reflection?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
9
3
September 5, 2022
Access Java field directly instead of using getter/setter - Language Design - Kotlin Discussions
For example, here is a Java class public class Thing { ... public int thing; public getThing() { return thing; } public setThing(int t) { thing = t; } } In Kotlin, if I want to access thing , I would do the following: val t = Thing() t.thing // get t.thing = 42 //set In the decompiled Kotlin ... More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
1
October 4, 2020
(Reflections) Get list of fields?
Did you ask on Stack Overflow ? I know the JetBrains Kotlin team regular post answers there. More on reddit.com
🌐 r/Kotlin
6
4
February 7, 2015
🌐
Baeldung
baeldung.com › home › java › core java › retrieve fields from a java class using reflection
Retrieve Fields from a Java Class Using Reflection | Baeldung
January 4, 2026 - Of course, we could use the getDeclaredFields() method on both Person and Employee classes and merge their results into a single array. But what if we don’t want to specify the superclass explicitly?
🌐
TutorialsPoint
tutorialspoint.com › javareflect › javareflect_field_get.htm
java.lang.reflect.Field.get() Method Example
The java.lang.reflect.Field.get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.
🌐
Dev.java
dev.java › learn › reflection › fields
Reading and Writing Fields - Dev.java
A Field object lets you get more information on the corresponding field: its type and its modifiers, and enables you to get the value of this field for a given object, and to set it.
🌐
Jenkov
jenkov.com › tutorials › java-reflection › fields.html
Java Reflection - Fields
April 21, 2016 - Class aClass = MyObject.class Field field = aClass.getField("someField"); MyObject objectInstance = new MyObject(); Object value = field.get(objectInstance); field.set(objetInstance, value); The objectInstance parameter passed to the get and ...
🌐
Bala's Blog
dkbalachandar.wordpress.com › 2017 › 03 › 08 › how-to-use-reflectionutils-to-retrieve-the-field-value
How to use ReflectionUtils to retrieve the field value | Bala's Blog
March 8, 2017 - import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.reflect.FieldUtils; import java.lang.reflect.Field; public class ReflectionUtilsMain { public static void main(String[] args) { Employee employee = new Employee(); employee.setEmpId("1234"); employee.setFirstName("John"); employee.setLastName("Turner"); employee.setDesignation("Manager"); System.out.println(employee); //Now you want to access the First Name from Employee object with Java reflection String firstName = null; String fieldName = "firstName"; for (Class aClass = employee.getClass(); aClass !=
Find elsewhere
🌐
Google Groups
groups.google.com › g › scala-user › c › DT1Ifw8YKvU
how to get value class fields with scala reflection
April 3, 2013 - It looks like that when using runtime reflection, foo becomes the int value (3) because it extends AnyVal. ... This behavior is expected or are we using the reflection API in a wrong way? I get the same result using SMirror: scala> implicit val mirror = scala.reflect.runtime.currentMirror · mirror: reflect.runtime.universe.Mirror = JavaMirror with scala.t...
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-reflection-example-tutorial
Java Reflection Example Tutorial | DigitalOcean
August 3, 2022 - If the field is final, the set() methods throw java.lang.IllegalAccessException. We know that private fields and methods can’t be accessible outside of the class but using reflection we can get/set the private field value by turning off the java access check for field modifiers.
🌐
Baeldung
baeldung.com › home › java › core java › get all record fields and its values via reflection
Get All Record Fields and Its Values via Reflection | Baeldung
January 16, 2024 - But, it “upgraded” to a permanent feature in Java 16. The RecordComponent class provides information about a component of a record class. Moreover, the Class class provides the getRecordComponents() method to return all components of a record class if the class object is a Record instance. It’s worth noting that the components in the returned array are in the same order declared in the record. Next, let’s see how to use RecordComponent together with the reflection API to get all fields from our Player record class and the corresponding values of the ERIC instance:
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-access-private-field-and-method-using-reflection-in-java
How to Access Private Field and Method Using Reflection in Java? - GeeksforGeeks
February 5, 2021 - // Access Private Field Using Reflection in Java import java.lang.reflect.Field; // Student class declaration class Student { // private fields private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } private int getAge() { return age; } public void setAge(int age) { this.age = age; } // Override toString method to get required // output at terminal @Override public String toString() { return "Employee [nam
🌐
Coderanch
coderanch.com › t › 378770 › java › reflection-final-static-field
Using reflection to get the value of a final static field (Java in General forum at Coderanch)
January 5, 2006 - In order to do this it needs to call the stored procedure with parameters extracted from an xml file. I've given each parameter an attribute sqltype which should take the name of one of the fields of java.sql.Types and then I'm using reflection to get the actual value of that field.
🌐
noredhomepage
noredhomepage.weebly.com › java-reflection-get-field-value-from-object.html
Java reflection get field value from object - noredhomepage
In order to access a private field ... of a public field, you can call the get() method of the Field object, with the object featuring the field value that you'd like to get as the first parameter....
🌐
Coderanch
coderanch.com › t › 443479 › java › Property-Field-Reflection
get Property-Field-Name via Reflection (Java in General forum at Coderanch)
April 30, 2009 - The answer is that there doesn't have to be any such field, by any name, so reflection cannot help you. For example, getX() might look like Even if the method returns a variable, it might be named "variableX" or "valueOfX" or anything; or it might be an element of an array, or a value in a HashMap, or a variety of other things. If you need to find this out about one particular class, you can disassemble it with the "javap" tool and look at the bytecode to see how the method is implemented.
🌐
Jaketrent
jaketrent.com › post › use-java-reflection-get-field-w-accessor
Use Java Reflection to Get Field w/ Accessor
The only stipulation to this working is that the class follows the JavaBean naming convention standard of "get" + capitalized field name following. Oh, and one more: this is only designed for @Entity's with one @Id field (no composite key). This method goes through all fields, finds the one with the javax.persistence.Id interface annotation, then tries to find a matching accessor method. If it is found, it is executed, the value of the id field is given, finally to be used to create the specially formatted string.
🌐
Spring
docs.spring.io › spring-framework › docs › 3.2.x › javadoc-api › org › springframework › core › annotation › AnnotationUtils.html
AnnotationUtils (Spring Framework 3.2.18.RELEASE API)
the Map of annotation attributes, ... as values · public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, boolean classValuesAsString, boolean nestedAnnotationsAsMap) Retrieve the given annotation's attributes as an AnnotationAttributes map structure. Implemented in Spring 3.1.1 to provide fully recursive annotation reading capabilities on par with that of the reflection-based ...
🌐
Reddit
reddit.com › r/learnjava › what’s the point of java reflection?
r/learnjava on Reddit: What’s the point of Java reflection?
September 5, 2022 -

I just watched a video showing some uses of reflection in Java, but honestly I can’t seem to comprehend why you’d go through that route with any program. For example, it was showing how you could alter the value of a final and/or private field. But what’s the point of adding 3+ extra lines of code when you could just change the type of the field?

Im not a Java veteran, but based on what I know, the concept of reflection seems unnecessary to me. Especially when the man who made the video, had as no1 argument as to why you should you use reflection that “it’s really cool”.

That’s why I’d like someone to briefly explain how it could genuinely be useful. Like, are there are any benefits that we couldn’t have without it ? In the video I watched there was something mentioned about frameworks which I haven’t worked with whatsoever, but I’m guessing that you’re still manipulating the api to get things done in a “cool” way.

Thank you in advance.

Top answer
1 of 9
9
In your normal applications you rarely use reflection yourself. It usually really is just a last resort thing to do if you need to get or set the value of a private field in a class that you need to extend. As the video you mentioned stated: The big use of reflection is in frameworks. Frameworks will use reflection to manipulate instances. They will allow you to use dependency injection, so that you dont need to care about where the required instances are coming from, you just get them and can use them. They will create and register event handlers based on annotations without you having to write any line of code besides the one annotation. Database frameworks will not make you deal with SQL result sets, instead they will give you a list of entity instances that they created via reflection. The framework wasnt built to specifically handle your Person entity for example. It is just able to accept any kind of entity because it can manipulate them via reflection. So in general frameworks will use reflection, accept that they have to write more code, so that the users of the framework can write less code. They do it so that the framework is as generic as possible. If you have never worked on larger projects and with large frameworks then this might not all make sense, but trust me reflection plays a huge role in saving time.
2 of 9
5
From a testing perspective, I read from a good book called “Working Effectively With Legacy Code” by Michael Feathers that it is best practice to not modify existing code in order to open up classes for testing. If you cant access these fields because they are marked private, reflection can be used to access these fields from outside the class. There can be regulatory reasons for not opening up fields for testing, and its better to not make edits to existing code if it can be avoided. EDIT: grammar
🌐
GraalVM
graalvm.org › jdk24 › reference-manual › native-image › metadata
GraalVM
Providing constant arguments in code is a preferred way to provide metadata as it requires no duplication of information in external JSON files. Reflection in Java starts with java.lang.Class that allows fetching further reflective elements such as methods and fields.
🌐
Kotlin Discussions
discuss.kotlinlang.org › language design
Access Java field directly instead of using getter/setter - Language Design - Kotlin Discussions
October 4, 2020 - For example, here is a Java class public class Thing { ... public int thing; public getThing() { return thing; } public setThing(int t) { thing = t; } } In Kotlin, if I want to access thing , I would do the following: val t = Thing() t.thing ...