Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

Invocation of methods of a dynamically loaded clas

Question:
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?

Answer:
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.");
      e.printStackTrace();
      return;
    }

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

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

}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

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