File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Class question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Class question" Watch "Class question" New topic

Class question

John Gregory
Ranch Hand

Joined: Oct 05, 2006
Posts: 118
I have an interface Task with one method, execute(). I have an xml file where
I have the classname of the Task I wish to create. What I'd like to do is iterate
through each of my nodes and run a particular task. But at runtime, I won't know
which task to run -- that's why I want the class name as an attribute. What I'd like
to do is something like this:

When I try this, I don't see the execute() function avail, which tells me I missed something,
somewhere. Does anyone have a better way to do this or see what I'm missing? Would a
ClassLoader be more appropriate? Aside from using the Class.forName for JDBC, I've not
really used the Class class.


Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195

This is fine as-is; people do this kind of thing all the time. The devil, as they say, is in the details, of course. We can help you get it right if we have a little more information. Can you explain what happens when you try it in a little more detail, please, and also cut and paste real code to show us -- sometimes the real code is wrong in some way even though the posted example is perfect.

[Jess in Action][AskingGoodQuestions]
John Gregory
Ranch Hand

Joined: Oct 05, 2006
Posts: 118

Maybe I mispoke in my last post. When I tried to run it, it seemed to be doing what
it was supposed to. I don't know what I did, maybe a typo somewhere...

Anyway, when you create a class in this fashion, how can you set up the resources
a class needs to "function". My problem is my tasks "do" different things, ldap queries,
jdbc queries where I need to use some resources. When I test each task by itself,
I do something like Task t = new Ldaptask(). In the constructor of Ldaptask, I create
my DirContext which allows me to do my ldap queries. From here, I can return a List
of whatever I want. But now, I'm not calling any constructor, so I'm not sure how to
create the resources I need for each task....

Rob Spoor

Joined: Oct 27, 2005
Posts: 20197

newInstance() does call a constructor - the constructor without any parameters.

If you need to invoke a different constructor, check out Class.getConstructor(s).

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Class question
It's not a secret anymore!