我试图检查对象是否在同一个包中有超类。
我做了以下例子
Vehicle.java
package myPackage;
public class Vehicle {
public Vehicle(){}
}
Car.java
package myPackage;
public class Car extends Vehicle{
public Car(){
super();
}
}
Main.java
1 package myPackage;
2
3 public class Main {
4
5 public static void main(String[] args){
6 Vehicle v = new Car();
7 hasSuperInSamePackage(v);
8 }
9
10 public static boolean hasSuperInSamePackage(Object o) {
11 boolean b = false;
12 if ((o.getClass().getSuperclass()) != null) {
13
14 Class c = o.getClass().getSuperclass();
15 Package objectPackage = o.getClass().getPackage();
16 Package superPackage = c.getClass().getPackage();
17 System.out.println("--begin--");
18 System.out.println("Object: " + o.toString());
19 System.out.println("objectPackageName: " + objectPackage.getName());
20 System.out.println("Super: " + c.toString());
21 System.out.println("superPackageName: " + superPackage.getName());
22 System.out.println("---end---");
23
24 b = (superPackage.getName().equals(objectPackage.getName()));
25 }
26 return b;
27 }
28 }
主要的输出如下
--begin--
Object: myPackage.Car@7852e922
objectPackageName: myPackage
Super: myPackage.Vehicle
superPackageName: java.lang
---end---
正如您所看到的,c.getClass()
[Main.16]采用类Class
的超类java.lang
,这是非常明显的。我想得到" myPackage"作为超类。我该怎么做?
答案 0 :(得分:2)
当您应该致电c.getClass().getPackage()
时,您正在致电c.getPackage()
。 c
已经是超类 - 它是Class
,因此在其上调用getClass()
只会给你Class.class
,这不是你想要的。
我会尝试更加一致,就像这样:
Class objectClass = o.getClass();
Class superClass = thisClass.getSuperclass();
Package objectPackage = objectClass.getPackage();
Package superPackage = superClass.getPackage();
System.out.println("--begin--");
System.out.println("Object: " + objectClass);
System.out.println("objectPackageName: " + objectPackage.getName());
System.out.println("Super: " + superClass);
System.out.println("superPackageName: " + superPackage.getName())