Run a java method by passing class name and method name as parameter

前端 未结 3 688
情深已故
情深已故 2021-01-14 09:04

I am trying to make a program that executes a particular method when the class name and method name are passed as String parameter to the caller. Consider the code below. I

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 09:35

    If all you are trying to do is call a method by name, you don't need to cast it to anything. It is sufficient to use the Object with further reflection.

    See Class.getDeclaredMethod(), as in:

    Object carObj = ...;
    Method method = carObj.getClass().getDeclaredMethod(methodName, ...);
    Object retObj = method.invoke(carObj, ...);
    

    Note that we don't care what type carObj actually is, although if you wanted to check you could always use instanceof or Class.isAssignableFrom or Class.isInstance.

    It is a bit weird, though, that you are instantiating a new object then calling one of its methods all in one go. That object goes away once your runTheMethod returns.


    By the way, it looks like you're just trying to get and set bean properties. You might want to have a look at Apache Commons BeanUtils instead, then your example becomes simply:

    CarBean bean = ...;
    String color = (String)PropertyUtils.getSimpleProperty(bean, "color"); // calls getter.
    

提交回复
热议问题