GeeCON Prague 2014*
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


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Class question" Watch "Class question" New topic
Author

Class question

John Gregory
Ranch Hand

Joined: Oct 05, 2006
Posts: 115
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.

Thanks,

John
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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: 115
Ernest,

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....

John
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

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

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
jQuery in Action, 2nd edition
 
subject: Class question