473,399 Members | 3,302 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Indirect references to classes?

I'm not sure what the correct name for this would be. I'd think it's either
an indirect reference, or a pointer, or something like that.

I'm working on a program that would call a series of classes in different
orders and there are times where I may add extra classes that weren't part
of the original design. I'd like to be able to store a list of the
classes, in the order that they are used, in a text file. Then I could
have the first class read in the text file and call the classes in order as
it goes through the text file. I don't want to have to hardcode a case
statement, calling each class if the line matches the name, since I want to
be able to easily add more classes in the future without re-compiling or
altering the original class.

If I have a classname stored in a String, is there any way to call that
class from the name stored in the string?

I know it can be done in Perl (I forget what it's called -- I think it's
"dereferencing"), like this:

&$function

and it will call the function that matches the name stored in $function.

Can I do something like this in Java?

Thanks!

Hal
Jul 17 '05 #1
3 5782
Hal Vaughan wrote:
I'm not sure what the correct name for this would be. I'd think it's either
an indirect reference, or a pointer, or something like that.

I'm working on a program that would call a series of classes in different
orders and there are times where I may add extra classes that weren't part
of the original design. I'd like to be able to store a list of the
classes, in the order that they are used, in a text file. Then I could
have the first class read in the text file and call the classes in order as
it goes through the text file. I don't want to have to hardcode a case
statement, calling each class if the line matches the name, since I want to
be able to easily add more classes in the future without re-compiling or
altering the original class.

If I have a classname stored in a String, is there any way to call that
class from the name stored in the string?

I know it can be done in Perl (I forget what it's called -- I think it's
"dereferencing"), like this:

&$function

and it will call the function that matches the name stored in $function.

Can I do something like this in Java?


Yes, Java is well suited for this task. The main tool for this is
reflection. Reflection lets you discover information about classes at
runtime.

There are a number of approaches, I recommend the following. Create an
interface that has the method on it you wish to call. Each class you
create would implement the interface. Use the Class.forName() method to
load each class named in your file. If you wish to be cautious you can
use Class.isAssignableFrom() to ensure the loaded Class implements the
interface. Use the Class.newInstance() method to create a instance of
the class. Cast the instance to you interface and invoke the method.

Ray

Jul 17 '05 #2
You can do this using reflection or polymorphism. So you have this
text-file with a list of classes in them (the classname). Now one of
the pre-requisites for this to work is that your ClassLoader has to
have the class in it's classpath. Call
Class clazz =
classLoader.loadClass("my.fully.qualified.class.na me");
This will return an object of type Class. Create a new instance by
using
Object o =clazz.newInstance();
Now you can use reflection to call a method on this object.

Alternatively once you have the object you can cast it to some type
(that you define) and then call the method on that type.
MyType myObject = (MyType) o;
myObject.doSomethingDynamically();

The second way is better because it provides some degree of
Type-Checking (although not much), although the first method allows
you to run a method thats not hard-coded at runtime.
Jul 17 '05 #3
Thanks for both responses. I had no idea where to look or under what topic
to search. Both posts gave me info on classes I had not learned about yet.
It also showed my reference book (Java 2 in Plain English, by Overland and
Morrison, published by M & T Books) is behind, since the class Class is not
in it at all (this books claims to be a full reference book to Java classes
and API).

I came up with two methods (acutally an overloaded method) to act as a
constructor for a class where I only have the name, or name and parameters.
They're pasted in below, along with sample calling code:

static Object getObject(String className) {
Object object = null;
try {
Class classDefinition = Class.forName(className);
object = classDefinition.newInstance();
} catch (Exception e) {System.out.println("Error w/ constructor: " + e);}
return object;
}

static Object getObject(String className, Object[] args) {
Object object = null;
Class[] argTypes = new Class[args.length];
for (int i = 0; i < args.length; i++) {
argTypes[i] = args[i].getClass();
}
try {
Class classDefinition = Class.forName(className);
Constructor classConstructor = classDefinition.getConstructor(argTypes);
object = classConstructor.newInstance(args);
} catch (Exception e) {System.out.println("Error w/ constructor[]: " + e);}
return object;
}

Be sure to add

import java.lang.reflect.Constructor;
import java.lang.Object;

at the start of the class you put these in.

For calling, if the constructor takes no args, call like this:

ClassName myObject = (ClassName) getObject("NameOfClassIWant");

For calling a constructor that takes args, call like this:

Object[] myParms = new Object[] {list, of, parameter, objects};
ClassName myObject = (ClassName) getObject("NameOfClassIWant", myParms);

Once you have myObject, you can use and abuse it like any other object.

Thanks, guys for the info.

I hope this helps a few others out there, since it provides a working way to
do this.

Hal

Hal Vaughan wrote:
I'm not sure what the correct name for this would be. I'd think it's
either an indirect reference, or a pointer, or something like that.

I'm working on a program that would call a series of classes in different
orders and there are times where I may add extra classes that weren't part
of the original design. I'd like to be able to store a list of the
classes, in the order that they are used, in a text file. Then I could
have the first class read in the text file and call the classes in order
as
it goes through the text file. I don't want to have to hardcode a case
statement, calling each class if the line matches the name, since I want
to be able to easily add more classes in the future without re-compiling
or altering the original class.

If I have a classname stored in a String, is there any way to call that
class from the name stored in the string?

I know it can be done in Perl (I forget what it's called -- I think it's
"dereferencing"), like this:

&$function

and it will call the function that matches the name stored in $function.

Can I do something like this in Java?

Thanks!

Hal


Jul 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Vera | last post by:
Hi, I have a very annoying problem, with which I NEED HELP DESPERATELY!! It smells like a bug to me, but I'm not sure. SITUATION This description is a very much simplified version of the real...
2
by: Steven T. Hatton | last post by:
Is there a way to forward declare a template? I've been trying to resolve a problem resulting from a recursive templet reference. The problem comes about when I attempt to #include a file which...
2
by: Christopher Burns | last post by:
Hi all, We are using VB.NET (VS2K3), sitting on VSS6. I have sorted out a configuration problem that was preventing us from building from scratch for new developers, but now I am having a very...
13
by: ganeshb | last post by:
Hi, What C statement(s) would translate to indirect jmp in assembly? I know that function pointer invocation would translate to indirect 'call' instruction, but I am not sure what will lead to...
14
by: el_sid | last post by:
Our developers have experienced a problem with updating Web References in Visual Studio.NET 2003. Normally, when a web service class (.asmx) is created, updating the Web Reference will...
3
by: Henning Möller | last post by:
I've got a solution with two projects. One of those (namespace MyProject.A) is using a library (e.g. Gentle.Framework). The other (namespace MyProject.B) is only using classes from MyProject.A. ...
2
by: Zioth | last post by:
class A { function Get() {return $this;} } $obj = new A(); In php5, the following statement is valid: $x = $obj->Get()->Get(); In php4, I get the following error:
1
by: jonathan184 | last post by:
Hi I amtrying to move over a website to another server. On the old hosting the site works fine. but when i transferred the site i am getting this error: Description: An error occurred during...
5
by: Rahul B | last post by:
Hi, I am having the following issues while trying to restrict the current user from creating any objects. Below is the privileges for the user and response when i try to create a table in that...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.