Link to home
Start Free TrialLog in
Avatar of bmarshallbri
bmarshallbri

asked on

Reflection from a Hashtable

So I'm pretty green to java still. What I have is a Hashtable that I have loaded with objects of my own classes.

I have put trace lines along with exception handling and I can see that the classes are successfully instantiated and loaded into the Hashtable and the Hashtable's size grows.

Once these objects are all created I need to then access them individually and  invoke their methods dynamically.  I have created all of my classes with the same method names and signatures so I can expect that each object in the hashtable has a method called set_filesource() for example. But these objects are not of the same class and do not implement any sort of interface.

The problem is I am not undrstanding Reflection quite yet nor do I grasp implementing Generics quite so well. So here's what I have right now. I can get this to compile fine because it's not checking the fact that the objects I load into the Hashtable are not of type Class. So when I run what's below I get a java.lang.ClassCastException: MyClass since the object in the Hashtable is of type MyClass not Class.

I'm wondering if I need to genericly cast my objects when I put them in the Hashtable or is there a way to generically cast the objects coming out of the Hashtable (which is what I'm attemptign here)? Otherwise is there a better way to dynamically invoke methods (with arguments) on objects of different classes in a Hashtable?


    private void executeMethod(String arg) {

        Class cl = (Class)MyHashtable.get(this.dataTarget);
        Object[] argObject = new Object[] {arg};
        String targetName = "set_"+methodTarget;

        try {  
            Method method = cl.getMethod(targetName,new Class[]{String.class});
            method.invoke(cl,argObject);
        }      
        catch (NoSuchMethodException ex) {
            // method does not exist
        }      
        catch (Exception ex) {
            ex.printStackTrace();
        }      

    }


Thanks for any help!
Avatar of bmarshallbri
bmarshallbri

ASKER

Never mind. I simplified and just created an interface so I didn't have to cast so generically.
ASKER CERTIFIED SOLUTION
Avatar of mukundha_expert
mukundha_expert

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have not tried it bu that makes sense.

I still need to call methods by name so when I implemented the interface on the objects and cast them like

MyClass cl = (MyClass)MyHashtable.get(this.dataTarget);

The following then worked.

Method method = cl.getClass().getMethod(targetName,new Class[]{String.class});
method.invoke(cl,argObject);


So I just went back and recast it as a generic per your example and it worked like a charm. So my problem was I was casting as Class instead of Object.

Thanks so much!!