java.lang.Class.cast how does it works?

Hi,

i used following code but always get a class cast Exception :-( Maybe i use it in a wrong way, can anybody help me?

Class clazz = getParameterTypes(methodName, instance);

Method method = instance.getClass().getMethod(methodName,new Class[]{ clazz});

method.invoke(instance, clazz.cast(parameter));

public Class getParameterTypes(String methodName, Object instance)

{

Method[] methods = instance.getClass().getMethods();

for (Method method : methods)

{

if(method.getName().equalsIgnoreCase(methodName))

{

return method.getParameterTypes()[0];

}

}

returnnull;

}

Note that "parameter" is always from type String, but sometimes the method which i invoke wants i.e. a value of type Long (or others), so i want to cast it.

In the method "getParameterTypes" i get the correct Type but when i try to do theclazz.cast(parameter) i always get a classcastException.

Anybody an idea how i can make it run, or know a workaround/other solution?

Thanks a lot.

Thomas

[1548 byte] By [OhNoa] at [2007-10-3 2:50:42]
# 1
>Note that "parameter" is always from type String, but sometimes the method >which i invoke wants i.e. a value of type Long (or others), so i want to cast it.You cannot cast an object which does not extend/implement the target class.
IanSchneidera at 2007-7-14 20:39:33 > top of Java-index,Java Essentials,Java Programming...