There is no linguistic support to do what you're asking for.
You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.
See also
- Java Tutorials: Reflection API / Advanced Language Topics: Reflection
Related questions
- What is reflection, and why is it useful?
- Java Reflection: Why is it so bad?
- How could Reflection not lead to code smells?
- Dumping a java object’s properties
Example
Here's a simple example to show only some of what reflection is capable of doing.
import java.lang.reflect.*;
public class DumpFields {
public static void main(String[] args) {
inspect(String.class);
}
static <T> void inspect(Class<T> klazz) {
Field[] fields = klazz.getDeclaredFields();
System.out.printf("%d fields:%n", fields.length);
for (Field field : fields) {
System.out.printf("%s %s %s%n",
Modifier.toString(field.getModifiers()),
field.getType().getSimpleName(),
field.getName()
);
}
}
}
The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:
7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER
Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection
These are excerpts from the book:
Answer from polygenelubricants on Stack OverflowGiven a
Classobject, you can obtainConstructor,Method, andFieldinstances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:
- You lose all the benefits of compile-time checking.
- The code required to perform reflective access is clumsy and verbose.
- Performance suffers.
As a rule, objects should not be accessed reflectively in normal applications at runtime.
There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.
There is no linguistic support to do what you're asking for.
You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.
See also
- Java Tutorials: Reflection API / Advanced Language Topics: Reflection
Related questions
- What is reflection, and why is it useful?
- Java Reflection: Why is it so bad?
- How could Reflection not lead to code smells?
- Dumping a java object’s properties
Example
Here's a simple example to show only some of what reflection is capable of doing.
import java.lang.reflect.*;
public class DumpFields {
public static void main(String[] args) {
inspect(String.class);
}
static <T> void inspect(Class<T> klazz) {
Field[] fields = klazz.getDeclaredFields();
System.out.printf("%d fields:%n", fields.length);
for (Field field : fields) {
System.out.printf("%s %s %s%n",
Modifier.toString(field.getModifiers()),
field.getType().getSimpleName(),
field.getName()
);
}
}
}
The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:
7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER
Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection
These are excerpts from the book:
Given a
Classobject, you can obtainConstructor,Method, andFieldinstances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:
- You lose all the benefits of compile-time checking.
- The code required to perform reflective access is clumsy and verbose.
- Performance suffers.
As a rule, objects should not be accessed reflectively in normal applications at runtime.
There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.
Accessing the fields directly is not really good style in java. I would suggest creating getter and setter methods for the fields of your bean and then using then Introspector and BeanInfo classes from the java.beans package.
MyBean bean = new MyBean();
BeanInfo beanInfo = Introspector.getBeanInfo(MyBean.class);
for (PropertyDescriptor propertyDesc : beanInfo.getPropertyDescriptors()) {
String propertyName = propertyDesc.getName();
Object value = propertyDesc.getReadMethod().invoke(bean);
}
Loop over all fields in a Java class - Stack Overflow
reflection - How to iterate through all properties of a Java bean - Stack Overflow
Better way of going about looping through all fields in a class I'm writing?
Java question:
How to loop through Student object attributes and check which fields are null?
import java.util.*;
import java.lang.reflect.Field;
//Student class
class Student{
private String name = "x";
private int age;
private int height;
private String gender;
private double grade;
// main method
public static void
Videos
Actually if you need only to read properties from a file and not to use these properties in Spring's property placeholders, then the solution is simple
public class Test1 {
@Autowired
Properties props;
public void printProps() {
for(Entry<Object, Object> e : props.entrySet()) {
System.out.println(e);
}
}
...
<util:properties id="props" location="/spring.properties" />
The @Value mechanism works through the PropertyPlaceholderConfigurer which is in turn a BeanFactoryPostProcessor. The properties used by it are not exposed at runtime. See this previous answer of mine for a possible solution.
Use getDeclaredFields on [Class]
ClasWithStuff myStuff = new ClassWithStuff();
Field[] fields = myStuff.getClass().getDeclaredFields();
for(Field f : fields){
Class t = f.getType();
Object v = f.get(myStuff);
if(t == boolean.class && Boolean.FALSE.equals(v))
// found default value
else if(t.isPrimitive() && ((Number) v).doubleValue() == 0)
// found default value
else if(!t.isPrimitive() && v == null)
// found default value
}
(http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html)
Yes, with reflection.
Use the Class object to access Field objects with the getFields() method.
Field[] fields = ClassWithStuff.class.getFields();
Then loop over the fields. This works because all fields you have declared are public. If they aren't, then use getDeclaredFields(), which accesses all Fields that are directly declared on the class, public or not.
getDeclaredFields()
for (Field field : yourObject.getClass().getDeclaredFields()) {
//do stuff
}
I strongly recommend to use an existing library and to avoid reflection in this case! Use JPA or Hibernate for database uses, use JAXB or similar for JSON/XML/other serialization, etc.
However, if you want to see what an example code would look like you can have a look at this:
package myOwnPackage;
import java.lang.reflect.Field;
class Address {
private String addr1;
private String addr2;
private String city;
private Zip zip;
}
class Contact {
private String phone;
private String email;
}
class Employee {
private String id;
private String name;
private int age;
private Address addr;
private Contact cont;
public void setAddr(Address addr) {
this.addr = addr;
}
}
class Zip {
private String zipCd;
private String zipExt;
}
public class Main {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
Employee employee = new Employee();
employee.setAddr(new Address());
printFields("", employee);
}
private static void printFields(String prefix, Object container) throws IllegalAccessException {
Class<? extends Object> class1 = null;
Package package1 = null;
if (container != null)
class1 = container.getClass();
if (class1 != null)
package1 = class1.getPackage();
if (package1 == null || !"myOwnPackage".equals(package1.getName())) {
System.out.println(container);
return;
}
for (Field field : class1.getDeclaredFields()) {
System.out.print(prefix+field.getName()+": ");
// make private fields accessible
field.setAccessible(true);
Object value = field.get(container);
printFields(prefix+" ", value);
}
}
}
Downsides of my code:
- This code uses reflection, so you are limited at the depth of fields
- Inherited fields are not printed
I'm writing a program as an opportunity to learn more about java from the ground up. I've encountered some classes where they include a properties hashmap of all the fields in a class, which I've found useful when writing log messages (since I'm using Selenium, it'd be nice to use this general string in log messages, for instance:
public String toString(){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(String.format("class %s's properties:",this.getClass())
properties.keySet().forEach(property -> {
stringBuilder.append(String.format(
"\n%30s:%s",property,properties.get(property)));
});
return stringBuilder.toString();
}I'm thinking the least invasive way of implementing this hashmap is to basically write a super getter? as opposed to storing all fields in said hashmap and making normal getters and setters go through the hashmap. ya? is there a better way to go about this altogether?
thanks for your input.