Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java Language
Expertise: Beginner
Feb 26, 1998



Application Security Testing: An Integral Part of DevOps

Invocation of methods of a dynamically loaded clas

I have two classes in two separate files. I don't want to use an interface because the types of objects I'll instantiate dynamically can be quite different each time. What can I do to call method without the use of an interfase?

Java 1.1 introduced a facility called reflection, through which the methods of a class can be discovered and invoked without compile-time knowledge of the class. You need to familiarize yourself with the classes in java.lang.reflect. Here is a rather contrived example showing how to call System.out.println() without invoking it directly. You will generally use reflection when you dynamically load a class of an unknown type, but with one or more known methods.

import java.lang.reflect.*;

public final class Reflect {

  public static final void main(String[] args) {
    Class outputClass, stringClass[];
    Object[] arguments;
    Method printlnMethod;

    outputClass = System.out.getClass();
    stringClass = new Class[1];
    stringClass[0] = String.class;

    try {
      printlnMethod = outputClass.getDeclaredMethod("println", stringClass);
    } catch(NoSuchMethodException e) {
      System.err.println("println does not exist.");

    arguments = new Object[1];
    arguments[0] = "Hello world!";

    try {
      printlnMethod.invoke(System.out, arguments);
    } catch(InvocationTargetException e) {
      System.err.println("invocation failed.");
    } catch(IllegalAccessException e) {
      System.err.println("invocation failed.");

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date