0rigami
2021-05-13 14:43
采纳率: 50%
浏览 46
已采纳

java反射找不到这个类

package study.ref;

import study.test.Dog;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;


public class ClassLoad {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入key");
        String key = scanner.next();
        switch (key) {
            case "1":
                Dog dog = new Dog();
                dog.hi();
                break;
            case "2":
                Class cls = Class.forName("Person");
                Object o = cls.getDeclaredConstructor().newInstance();
                Method m = cls.getMethod("hi");
                m.invoke(o);
                System.out.println("ok");
                break;
            default:
                System.out.println("do nothing..");
        }
    }
}

class Person {
    public void hi() {
        System.out.println("打招呼");
    }
}

为什么找不到这个Person类?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • GreyZeng 2021-05-13 15:07
    已采纳

    Class cls = Class.forName(Person.class.getCanonicalName());

    已采纳该答案
    1 打赏 评论
  • _寻隐者不遇 2021-05-13 14:50

    Class cls = Class.forName("Person");

    person的包名也要写

    1 打赏 评论
  • Class.forName(“study.ref.ClassLoad.Person”)这样写

     

    1 打赏 评论

相关推荐 更多相似问题