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" />
Answer from Evgeniy Dorofeev on Stack Overflow
🌐
Tabnine
tabnine.com › home page › code › java › java.util.properties
Java Examples & Tutorials of Properties.forEach (java.util) | Tabnine
private static MultiValueMap<String, Entry> parseIndex(List<Properties> content) { MultiValueMap<String, Entry> index = new LinkedMultiValueMap<>(); for (Properties entry : content) { entry.forEach((type, values) -> { String[] stereotypes = ((String) values).split(","); for (String stereotype : stereotypes) { index.add(stereotype, new Entry((String) type)); } }); } return index; }
🌐
Boraji
boraji.com › how-to-iterate-properites-in-java
https://boraji.com/how-to-iterate-properites-in-java
March 1, 2017 - In this post, we will show you how to iterate the java.util.Properties using - java.util.Enumeration · For-Each loop + Properties's stringPropertyNames() method · For-Each loop + entry set · forEach() method ( Introduced in Java 8) The propertyNames() method of the Properties return an ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › properties-foreachbiconsumer-method-in-java-with-examples
Properties forEach(BiConsumer) method in Java with Examples - GeeksforGeeks
July 11, 2025 - import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put("Pen", 10); properties.put("Book", 500); properties.put("Clothes", 400); properties.put("Mobile", 5000); // Print Properties details System.out.println("Properties 1: " + properties.toString()); // Add 100 in each value using forEach() properties.forEach((k, v) -> { v = (int)v + 100; properties.replace(k, v); }); // Print new mapping using forEcah() properties.forEach( (k, v) -> System.out.println("Key : " + k + ", Value : " + v)); } }
🌐
Program Creek
programcreek.com › java-api-examples
Java Code Examples for java.util.Properties#forEach()
public static void load() { Properties sysEvn = new Properties(); try { URL sysEnvFileUrl = SystemConfigLoader.class.getClassLoader().getResource(SYSTEM_EVN_FILE); if(null != sysEnvFileUrl) { logger.info("Found system properties file: {}.", sysEnvFileUrl); sysEvn.load(sysEnvFileUrl.openStream()); } else { logger.info("No system properties file in classpath, using default properties."); sysEvn = DEFAULT_PROPERTIES; } } catch (IOException e) { logger.warn("load system config exception, using default.", e); sysEvn = DEFAULT_PROPERTIES; } sysEvn.forEach((k, v) -> { logger.info("Set system property: {} -> {}.", k, v); System.setProperty(k.toString(), v.toString()); }); }
Top answer
1 of 7
116

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 Class object, you can obtain Constructor, Method, and Field instances 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.

2 of 7
49

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);
}
Find elsewhere
🌐
Coderanch
coderanch.com › t › 397254 › java › Property-File-Iteration
Property File Iteration (Beginning Java forum at Coderanch)
September 29, 2004 - I'm trying to get a list of the key/value pairs in a property file without using the java.util.Properities.list() method. This is what I have thus far:.
🌐
Jenkov
jenkov.com › tutorials › java-collections › properties.html
Java Properties
Here is an example of removing a property from a Java Properties instance: ... You can iterate the keys of a Java Properties instance by obtaining the key set for the Properties instance, and iterating this key set.
🌐
Coderanch
coderanch.com › t › 599586 › java › Properties-Class
for-each and Properties Class [Solved] (Beginning Java forum at Coderanch)
December 5, 2012 - Why not loop over the entry set? Unfortunately you'll need those casts since somebody thought that Properties should extend Hashtable<Object, Object> instead of Hashtable<String, String>, probably because someone somewhere abused Properties and put something other than Strings in it.
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › util › Properties.html
Properties (Java SE 9 & JDK 9 )
These iterators are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction. The load(Reader) / store(Writer, String) methods load and store properties from and to a character based ...
🌐
Blogger
sailendra-jena.blogspot.com › 2013 › 04 › how-to-iterate-properties-files-in-java.html
Java By Sailendra: How to iterate Properties Files in Java?
April 23, 2013 - 1. Properties props = System.getProperties(); for (String key : props .stringPropertyNames()) { System.out.println(key + " = " + props .getProperty(key)); } 2. Properties props = System.getProperties(); Enumeration e = props.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); System.out.println(key + " = " + props.getProperty(key)); } 3. Properties props = System.getProperties(); SortedMap sortedSystemProperties = new TreeMap(props); Set keySet = sortedSystemProperties.keySet(); Iterator iterator = keySet.iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); System.out.println(key + " = " + props .getProperty(key)); }
🌐
Google Groups
groups.google.com › g › jenkinsci-users › c › ti6UINYeogA
Jenkinsfile: How to iterate a properties file without having an "java.io.NotSerializableException: java.util.Hashtable$Entry" error
October 13, 2016 - node('master') { Properties properties = new Properties() properties.load(new FileInputStream("${env.JENKINS_HOME}\\properties\\${file}")) for(Entry<Object, Object> en : properties.entrySet()) { System.out.println(en); } /*for(Object k:properties.keySet()) { String key = (String) k; } */ // same error /* Enumeration en = properties.propertyNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); System.out.println(key + " -- " + properties.getProperty(key)); }*/ // same error } java.io.NotSerializableException: java.util.Hashtable$Entry at org.jboss.marshalling.river.Riv
🌐
Stack Overflow
stackoverflow.com › questions › 28326842 › java-iterate-through-properties-file
smtp - java iterate through properties file - Stack Overflow
June 11, 2017 - I have a project to send emails via a Java Application. I have almost everything working, I just need to be able to configure the number of emails I send. I have all of the email addresses in a Properties File. The application spec requires me to set a value in this file that will determine the number of emails to send. Here is an example of my properties file, in the hope that this helps: email1=tom@foo.com email2=jerry@foo.com email3=spike@foo.com iterate=1 //this is the value that needs to be changed in order to decide the number of emails to send.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Properties.html
Properties (Java SE 11 & JDK 11 )
January 20, 2026 - These iterators are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction. The load(Reader) / store(Writer, String) methods load and store properties from and to a character based ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Properties.html
Properties (Java Platform SE 8 )
2 weeks ago - Java™ Platform Standard Ed. 8 ... The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream.