菜鸡『』 2022-05-12 11:46 采纳率: 100%
浏览 24
已结题

Java|构造函数能不能使用invoke()方法?

Java中构造函数能不能使用invoke()方法?

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

class Q{
    private String name; private boolean gender; private int age; private double score;
    public Q(){
        this.name = "none"; this.gender = false; this.age = 0; this.score = 0;
    }
    public Q(String name, boolean gender, int age, double score){
        this.name = name; this.gender = gender; this.age = age; this.score = score;
    }
    public void set(String name, boolean gender, int age, double score){
        this.name = name; this.gender = gender; this.age = age; this.score = score;
    }
    public String toString(){
        return "name:"+this.name+", gender:"+this.gender+", age:"+this.age+", score:"+this.score;
    }
}
public class invokeDemo{
    public static void main(String[] args){
        Class<?> c = null;
        try{
            c = Class.forName("Q");
        } catch(Exception e){
            e.printStackTrace();
        }
        try{
            Method m3 = c.getMethod("Q");
            Method m4 = c.getMethod("Q", String.class, boolean.class, int.class, double.class);
            System.out.println(m3.invoke(c.newInstance()));
            System.out.println(m4.invoke(c.newInstance(), "大大", true, 19, 100.9999));
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

运行结果如下:
java.lang.NoSuchMethodException: Q.Q()
at java.base/java.lang.Class.getMethod(Class.java:2227)
at invokeDemo.main(invokeDemo.java:45)
嗯嗯...NoSuchMethodException发生在Method m3 = c.getMethod("Q");这一行。

这样看来构造方法不能使用invoke()方法了?或者说我使用的方法不正确?
欢迎讨论、解答!

  • 写回答

2条回答 默认 最新

  • zlebhs 2022-05-12 12:33
    关注

    Method是Method,Constructor是Constructor
    你想要的应该是

            Constructor<Q> constructor = Q.class.getConstructor(String.class, boolean.class, int.class, double.class);
            Q q = constructor.newInstance("1", true, 0, 0.0);
            System.out.println(q);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月27日
  • 已采纳回答 5月19日
  • 创建了问题 5月12日

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?