Java Reflection Tutorial – List Methods Of A Class

Reflection is a very powerful tool in Java. I will start this tutorial with an excerpt from Sun’s Tutorial Page for Java reflections. It says:

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

  • Extensibility Features
    An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
  • Class Browsers and Visual Development Environments
    A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.
  • Debuggers and Test Tools
    Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

  • Performance Overhead
    Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
  • Security Restrictions
    Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
  • Exposure of Internals
    Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

The following tutorial will use the class called Student and display all the methods of that class using the Java Reflection technology.

package com.kushal.utils;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 10th August 2009
 *
 * A Simple class that lists the method of another
 * class using the reflections mechanism.
 */
import java.lang.reflect.Method;

public class MethodsListViaReflection {

	public void listMethods() {

		Class myStudentClass = Student.class;

		Method[] methods = myStudentClass.getDeclaredMethods();

		for (Method method : methods) {
			System.out.println(method.getName());
		}
	}

	public static void main(String[] args) {
		new MethodsListViaReflection().listMethods();
	}
}

class Student {

private String _firstname;
private String _lastname;
private String _address;
private int _rollNumber;

public String getFirstname() {
return _firstname;
}

public void setFirstname(String firstname) {
_firstname = firstname;
}

public String getLastname() {
return _lastname;
}

public void setLastname(String lastname) {
_lastname = lastname;
}

public String getAddress() {
return _address;
}

public void setAddress(String address) {
_address = address;
}
public int getRollNumber() {
return _rollNumber;
}

public void setRollNumber(int rollNumber) {
_rollNumber= rollNumber;
}
}[/java]
=======================
The following is the output of this program:
getFirstname
setFirstname
getLastname
setLastname
getAddress
setAddress
getRollNumber
setRollNumber

  1. How to extract plain Text from HTML Website easily in Java
  2. How To Find What Java Version You Are Using?
  3. Computing the total, free and usable disk space easily using JDK 1.6
  4. Creating java.util.date and java.util.sql objects from Calendar object
  5. Bar Code Generation In Java Using iText API
  6. Simple Tag Generator In Java For Music Blogs
  7. Tutorial on Converting an List of Strings or Numbers to a CSV file with optional sorting
  8. Calling URL Browser From Java Application
  9. Java Reflection Tutorial – List Methods Of A Class
  10. Cleaning Punctuation And White Spaces From A String
  11. Java Tutorial – Using JCIFS to copy files to shared network drive using username and password
  12. Prime Number Finder In Java
  13. Utility Class For Getting SQL Connection and Closing It
  14. Java Design Pattern – Singleton Pattern
  15. Reading / Writing File in Java and String Manipulation
  16. How to capture a screenshot using Java and save it to a file?
  17. Calculating The Difference Between Two Dates In Terms of Months
  18. Getting The Name Of Currently Logged In User In The System
  19. How To Set And Get System Clipboard Contents In Java
  20. RGB To Hex and Hex To RGB Conversion Using Java and Regular Expressions
  21. Java Reflections Tutorial
  22. Generating Nepali Unicode Sequence For Characters
  23. Java Tool To Compare Two Lists and Spit Out The Differences – Working Example
  24. Replacing non-ASCII characters using Java Regular Expressions
  25. Calculating Folder Size In Java
Tagged , , , , , , , , . Bookmark the permalink.

3 Responses to Calculating Folder Size In Java

  1. Pingback: Sanjaal.com » Latest Updates

  2. Jamie says:

    This approach uses less memory:

    public static class SizeCounter implements FileFilter
    {
    private long total = 0;
    public SizeCounter(){};
    public boolean accept(File pathname) {
    if ( pathname.isFile()) {
    total+=pathname.length();
    } else {
    pathname.listFiles(this);
    }
    return false;
    }
    public long getTotal()
    {
    return total;
    }
    }

    private static long getFileOrDirectorySize(File file) {
    SizeCounter counter = new SizeCounter();
    file.listFiles(counter);
    return counter.getTotal();
    }

  3. kushalzone says:

    Thank you Jamie for your optimized solution.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.