有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何从类中获取方法。Java中的forName()?

已编辑

我有一个未知的类,只有名为namo的字符串变量知道,它的方法名为paintah,带有Graphics g参数。现在我正努力做到:

Class.forName(namo).getMethod("paintah", ??????????);    

我应该用什么来代替问号?我花了好几个小时想弄明白

同样,如果我使用相同代码的同一个类(但只有我知道它的名称Classo),如下所示:

new Classo.paintah(g);    

它起作用了

更新 我有两个类,一个有这部分代码:

public static Classo cla = new Classo();
 public void paintComponent(Graphics g){
       Class.forName(namo).getMethod("paintah", Graphics.class); //not working
       cla.paintah(g); // working
}

也就是说,主类,Classo的代码与未知类的代码相同,它有这部分代码:

public void paintah(Graphics g){
       g.fillRect(20,20,200,200);
}

所以是的,我希望这能给你一个更好的主意


共 (3) 个答案

  1. # 1 楼答案

    如果你有以下课程:

    public class MyClass
    {
       public void MyMethod(MyParameterType param);
    }
    

    然后你可以得到如下的方法对象:

    Class.forName("MyClass").getMethod("MyMethod", MyParameterType.class);
    

    getMethod()javadoc:

    The name parameter is a String specifying the simple name of 
    the desired method. The parameterTypes parameter is an array of 
    Class objects that identify the method's formal parameter types, 
    in declared order. If parameterTypes is null, 
    it is treated as if it were an empty array. 
    
  2. # 3 楼答案

    您正在使用^{}方法,该方法接受Class对象的varargs参数,这些对象表示目标方法中的参数类型

    如果只需要一个Graphics对象,那么提供Graphics.class

    Class.forName("bla").getMethod("paintah", Graphics.class);
    

    因为你知道类名,你甚至不需要Class.forName,你可以使用类文本来访问它

    bla.class.getMethod("paintah", Graphics.class);
    

    无论如何,您都需要捕获从getMethod调用中抛出的Exceptions

    Throws:

    NoSuchMethodException - if a matching method is not found or if the name is ""or "". NullPointerException - if name is null SecurityException - If a security manager, s, is present and any of the following conditions is met:

    • invocation of s.checkMemberAccess(this, Member.PUBLIC) denies access to the method

    • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class