我该如何处理 ClassNotFoundException?
How do I go about ClassNotFoundException?
public class Point {
int x, y;
Point() { System.out.println("default"); }
Point(int x, int y) { this.x = x; this.y = y; }
static Point origin = new Point(0,0);
public String toString() { return "(" + x + "," + y + ")"; }
}
class Test {
public static void main(String[] args) {
Point p = null;
try {
p = (Point)Class.forName("Point").newInstance();
} catch (Exception e) {
System.out.println(e);
}
Point a[] = { new Point(0,0), new Point(1,1) };
System.out.println("p: " + p);
System.out.println("a: { " + a[0] + ", " + a[1] + " }");
}
}
它应该产生:
默认
p: (0,0)
一个:{(0,0),(1,1)}
但它产生了:
java.lang.ClassNotFoundException: 点
p: 空
一个:{(0,0),(1,1)}
添加完全限定名称解决了问题。对我来说,main
是包的名称:
p = (Point)Class.forName("main.Point").newInstance();
public class Point {
int x, y;
Point() { System.out.println("default"); }
Point(int x, int y) { this.x = x; this.y = y; }
static Point origin = new Point(0,0);
public String toString() { return "(" + x + "," + y + ")"; }
}
class Test {
public static void main(String[] args) {
Point p = null;
try {
p = (Point)Class.forName("Point").newInstance();
} catch (Exception e) {
System.out.println(e);
}
Point a[] = { new Point(0,0), new Point(1,1) };
System.out.println("p: " + p);
System.out.println("a: { " + a[0] + ", " + a[1] + " }");
}
}
它应该产生:
默认 p: (0,0) 一个:{(0,0),(1,1)}
但它产生了:
java.lang.ClassNotFoundException: 点 p: 空 一个:{(0,0),(1,1)}
添加完全限定名称解决了问题。对我来说,main
是包的名称:
p = (Point)Class.forName("main.Point").newInstance();