dcsimg
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

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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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