I'm trying to check if an object has a superclass in the same package.
I made the following example
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 }
The output of the main is the following
--begin--
Object: myPackage.Car@7852e922
objectPackageName: myPackage
Super: myPackage.Vehicle
superPackageName: java.lang
---end---
As you can see the c.getClass()
[Main.16] takes the superclass of the class Class
which is java.lang
which is quite obvious. I want to get "myPackage" as the superclass. How do I do this?
You're calling c.getClass().getPackage()
when you should be calling c.getPackage()
. c
is already the superclass - it's a Class
, so calling getClass()
on it will just give you Class.class
, which isn't what you want.
I would try to be more consistent about it, like this:
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())
See more on this question at Stackoverflow