JAVA小白求助反射问题
F:\JAVA\bin\java.exe "-javaagent:F:\JAVAIJ\IntelliJ IDEA Community Edition 2021.1.3\lib\idea_rt.jar=4518:F:\JAVAIJ\IntelliJ IDEA Community Edition 2021.1.3\bin" -Dfile.encoding=UTF-8 -classpath F:\JAVA\IJ\xiangmu\反射\out\production\反射 反射案例.ReflectTestException in thread "main" java.lang.ClassNotFoundException: åå°è·åæé æ1æ3å1¶ä½¿ç¨.Student
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:375)
at 反射案例.ReflectTest.main(ReflectTest.java:26)
大佬们,上面这是报错信息,下面是代码,可以帮忙看下这是啥情况吗,多谢大佬们
package 反射案例;
//
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectTest {
public static void main(String[] args) throws Exception {
//加载配置类文件:
//1,创建Properties
Properties pro = new Properties();
//2.加载配置文件,转换为一个集合
//2.2获取Class目录下的配置文件
ClassLoader classLoader = ReflectTest.class.getClassLoader();//获取对应的类加载器
InputStream is= classLoader.getResourceAsStream("pro.properties");//返回字节流
pro.load(is);
//获取配置文件中定义的数据
String calssNames = pro.getProperty("ClassName1");
String methodName = pro.getProperty("MethondName1");
//加载该类进内存
Class cls = Class.forName(calssNames);
//创建对象
Object obj = cls.getDeclaredConstructor().newInstance();
//获取方法对象
Method method = cls.getMethod(methodName);
//执行方法
method.invoke(obj);
}
}
=================================================
pro.propertise文件
ClassName1=反射获取构造方法并使用.Student
MethondName1=eat
=================================================
Student.java
package 反射获取构造方法并使用;
public class Student {
private String name;
private int age;
public String a;
String b;
@java.lang.Override
public java.lang.String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", a='" + a + '\'' +
", b='" + b + '\'' +
'}';
}
private void methodt1(){
System.out.println("methodt1...");
}
public Student() {
}
public Student(String name, int age, String a, String b) {
this.name = name;
this.age = age;
this.a = a;
this.b = b;
}
public String getName() {
System.out.println("getname");
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
private void Mode(){
System.out.println("Mode...");
}
public void eat() {
System.out.println("eat...");
}
}
如果有中文路径的话会出现乱码
报错信息:encoding=UTF-8 -classpath F:\JAVA\IJ\xiangmu\反射\out\production\反射 反射案例.ReflectTest,,也说明这个路径输出有问题,推测应该是中文出现反射失败
把Studebt类的包名改为英文,再配置一下properties文件
页:
[1]