Get parent class from child class - java

I have a method that accepts a single parameter. That parameter can be any class A, B, C, or D that all inherit from the same parent class E. I do not know the name of the parent class, however (maybe it's "E" maybe it's "F").
I want my method to accept as a parameter the parent class, so I can pass in a child object (so I only need one implementation of the method).
How do I find the name of the parent class? It is in a jar that I do not have source code access to.
EDIT
Example of what method will look like:
private void processResults(final ???parentClassName??? aParentClassName) {
...
}

Try with Class#getSuperclass()
Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.
If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.
If this object represents an array class then the Class object representing the Object class is returned.
sample code:
A.class.getSuperclass().getName()
or
aObject.getClass().getSuperclass().getName()

You can use the javap tool that comes with the JDK.
Suppose your jar file is named unknown.jar and that the package for class A whose parent class you are interested in is com.example.unknown.
You can do this:
javap -classpath unknown.jar com.example.unknown.A
And the output will be something like:
Compiled from "A.java"
public class com.example.unknown.A extends com.example.unknown.E {
public com.example.unknown.A();
}
It will also show you the public API of A. It can show you more information, too, depending on the command line parameters you pass. Use javap -help to see them all.
(Note: You may need to specify additional jars or directories to the -classpath parameter, if unknown.jar has other dependencies.)

If you don't know the superclass / the name of the superclass it's impossible, I think.
If there are only 4 classes, why don't you just create an interface and let your classes A to D inherit them? Might be easier :)

Related

Every class is implicitly a subclass of Object Java

I'm reading Java Inheritance Docs and got this paragraph, but I don't what is mean of this. Can any body explain?
Excepting Object, which has no superclass, every class has one and
only one direct superclass (single inheritance). In the absence of any
other explicit superclass, every class is implicitly a subclass of
Object.
Edited
Another point related to this question:
And due to Object is superclass, NetBeans show me extra method list when I try to call any Member of class with object reference? All those methods are declared in Object class?
It means that,in java the Object class is the parent class of all the classes by default. In other words, it is the topmost class or the base class of java. All other classes inherit the properties of Object class.
Meaning of implicitly - suggested though not directly expressed.
If samething applied in Java classes. Consider there is a class called Test.
If you write
public class Test {....}
That is equivalent to
public class Test extends Object {....}
Though you didn't write it, it's equivalent to it. You need not to write extends Object manually. Internally JVM treats that your class is extends Object. Since the part after extends is your class, here Object is your super class.
But,
When you write
public class Test extends BigTest{....}
Things changed now. You are telling BigTest is my parent class. That means you are implicitly writing yourself that BigTest is my parent. Interesting part here is though BigTest is your direct Parent class, internally Object also your Parent.
So now you have 2 parent classes. One is BigTest which you mentioned and other is Object. If you didn't mention anything, only Object is your Parent.
Edit :
This is the reason that you will see extra list of method when you will try to call any member of class with object-reference. Those methods are declared in Object class.
why java do this? any feature of this?
Yes. There are benefits of it. Main reason is to reduce the code duplication.
Continue reading here .... Why Object as super class in Java ?
It means that the following two classes are the same:
class MyClass {
}
class MyClass extends Object {
}
If a class definition doesn't specify extends, the class implicitly extends Object.
The Object class comes with the JRE, you use any class without it. Java does this so you can have a reference to any object e.g.
Object o = x;
This works because no matter what x is, it is also an Object.
Note: even int[] class is a sub-class of Object.

What does .class mean after a class name

What does .class mean in, for example, MyClass.class? I understand that when you put the name of a class and the point it is used to access its static fields or methods, but that doesn't relate to '.class'
SomeClass.class gets the Class<SomeClass> type which you can use for programming using the reflection API.
You can get the same type if you have an instance of the class using instance.getClass().
You can check out the documentation here. For example, you can:
get the names of fields and methods, annotations, etc.
invoke methods, get constructor to create new instances of the class
get the name of the class, the superclass, package, etc
When you write .class after a class name, it references the Class object that represents the given class (formally, it is a named class literal). The the type of NombreClase.class is Class<NombreClase>.
E.g., NombreClase.class is an object that represents the class NombreClase on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of NombreClase.
NombreClase obj = new NombreClase();
System.out.println(NombreClase.class.getName());
System.out.println(obj.getClass().getName())
You can add .class to the name of any class to retrieve an instance of its Class object.
When you use Integer.class you reference an instance of Class<Integer>, which is a typed class object.
I always thought this was a field member that got added by the compiler, but it looks like it's really just syntactic sugar.

Difference between MyClass.class and Class.forName("className")

We can get class Class object by 3 methods:
MyClass.class
obj.getClass
Class.forName("className")
I don't understood the difference between: MyClass.class and Class.forName("className").
Because both will need Class Name.
Class.forName("className");
forName is a static method of class "Class".
we require to provide the fully qualified name of the desired class.
this can be used when name of class will come to known at runtime.
ClassName.class;
.class is not a method it is a keyword and can be used with primitive type like int.
when Name of Class is known in advance & it is added to project, that time we use ClassName.class
I don't understood the difference between: MyClass.class and Class.forName("className").
Because both will need Class Name.
The big difference is when they need it. Since Class.forName accepts a string, the class name can be determined at runtime. Whereas of course, MyClass.class is determined at compile-time. This makes Class.forName useful for dynamically loading classes based on configuration (for instance, loading database drivers depending on the settings of a config file).
Rounding things out: obj.getClass() is useful because you may not know the actual class of an object — for instance, in a method where you accept an argument using an interface, rather than class, such as in foo(Map m). You don't know the class of m, just that it's something that implements Map. (And 99% of the time, you shouldn't care what its class is, but that 1% crops up occasionally.)
Class.forName("className");
It dynamically load the class based on fully qualified class name string.
obj.getClass
Returns the java.lang.Class object that represents the runtime class of the object.
MyClass.class:
A class literal is an expression consisting of the name of a class, interface, array,
or primitive type, or the pseudo-type void, followed by a'.' and the token class.
The type of C.class, where C is the name of a class, interface, or array type is Class<C>.
http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf
One important difference is:
A.class will perform loading and linking of class A.
Class.forName("A") will perform loading, linking and initialization of class A.

what is the Class object (java.lang.Class)?

The Java documentation for Class says:
Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
What are these Class objects? Are they the same as objects instantiated from a class by calling new?
Also, for example object.getClass().getName() how can everything be typecasted to superclass Class, even if I don't inherit from java.lang.Class?
Nothing gets typecasted to Class. Every Object in Java belongs to a certain class. That's why the Object class, which is inherited by all other classes, defines the getClass() method.
getClass(), or the class-literal - Foo.class return a Class object, which contains some metadata about the class:
name
package
methods
fields
constructors
annotations
and some useful methods like casting and various checks (isAbstract(), isPrimitive(), etc). the javadoc shows exactly what information you can obtain about a class.
So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the #Processable annotation, then:
public void process(Object obj) {
if (obj.getClass().isAnnotationPresent(Processable.class)) {
// process somehow;
}
}
In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Class instance are called "reflective operations", or simply "reflection. Read here about reflection, why and when it is used.
Note also that Class object represents enums and intefaces along with classes in a running Java application, and have the respective metadata.
To summarize - each object in java has (belongs to) a class, and has a respective Class object, which contains metadata about it, that is accessible at runtime.
A Class object is sort of a meta object describing the class of an object. It is used mostly with the reflection capabilities of Java. You can think of it like a "blueprint" of the actual class. E.g. you have a class Car like this:
public class Car {
public String brand;
}
You can then construct a Class object which describes your "Car" class.
Class myCarClass = Class.forName("Car");
Now you can do all sorts of querying on your Car class on that Class object:
myCarClass.getName() - returns "Car"
myCarClass.getDeclaredField("brand") - returns a Field object describing the "brand" field
and so on. Every java object has a method getClass() which returns the Class object describing the Class of the Java object. So you could do something like:
Car myCar = new Car();
Class myCarClass = myCar.getClass();
This also works for objects you don't know, e.g objects you get from the outside:
public void tellMeWhatThisObjectsClassIs(Object obj) {
System.out.println(obj.getClass().getName());
}
You could feed this method any java object and it will print the actual class of the object you have given to it.
When working with Java, most of the time you don't need to worry about Class objects. They have some handy use cases though. E.g. they allow you to programmatically instanciate objects of a certain class, which is used often for object serialization and deserialization (e.g. converting Java Objects back and forth to/from XML or JSON).
Class myCarClass = Class.forName("Car");
Car myCar = myCarClass.newInstance(); // is roughly equivalent to = new Car();
You could also use it to find out all declared fields or methods of your class etc, which is very useful in certain cases. So e.g. if your method gets handed an unknown object and you need to know more about it, like if it imlements some interface etc, the Class class is your friend here.
So long story short, the Class, Field, Method, etc. classes which are in the java.lang.reflect package allow you to analyze your defined classes, methods, fields, create new instances of them, call methods all kinds of other stuff and they allow you to do this dynamically at runtime.
getClass() is a method that returns an object that is an instance of java.lang.Class... there is no casting involved. Casting would look like this:
Class<?> type = (Class<?>) object;
I would also like to add to ColinD 's answer that getClass will return the same object for instances of same type. This will print true:
MyOtherClass foo = new MyOtherClass();
MyOtherClass bar = new MyOtherClass();
System.out.println(foo.getClass()==bar.getClass());
Note that it is not equals, I am using ==.
In order to fully understand the class object, let go back in and understand we get the class object in the first place. You see, every .java file you create, when you compile that .java file, the jvm will creates a .class file, this file contains all the information about the class, namely:
Fully qualified name of the class
Parent of class
Method information
Variable fields
Constructor
Modifier information
Constant pool
The list you see above is what you typically see in a typical class. Now, up to this point, your .java file and .class file exists on your hard-disk, when you actually need to use the class i.e. executing code in main() method, the jvm will use that .class file in your hard drive and load it into one of 5 memory areas in jvm, which is the method area, immediately after loading the .class file into the method area, the jvm will use that information and a Class object that represents that class that exists in the heap memory area.
Here is the top level view,
.java --compile--> .class -->when you execute your script--> .class loads into method area --jvm creates class object from method area--> a class object is born
With a class object, you are obtain information such as class name, and method names, everything about the class.
Also to keep in mind, there shall only be one class object for every class you use in the script.
Hope this makes sense
A Class object is an instance of Class (java.lang.Class). Below quote taken from javadoc of class should answer your question
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method

Classes not extending java.lang.Object

While you create a user defined class in Java, you do not specify it as extending Object. But still the class is an Object. How does this work? How does javac or the JVM inject all properties of a class to the user defined class?
If you don't actually write extends Object, the compiler inserts it for you.
EDIT: Apparently I caused some confusion about whether there is actually an insertion of code going on. I wasn't entirely sure myself so I ran a little experiment: create the following class in file test.java:
public class test {}
and compile it, then run
javap -c test
to disassemble the bytecode. Look what comes out:
Compiled from "test.java"
public class test extends java.lang.Object{
public test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
}
So yes, the compiler does actually insert extends java.lang.Object (or the bytecode equivalent) into the class.
All java classes implicitly extend java.lang.Object. From the documentation:
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Here's a link to JVM spec as well:
The standard class Object is the superclass (§2.8.3) of all other classes. A variable of type Object can hold a reference to any object, whether it is an instance of a class or an array. All class and array types inherit the methods of class Object.
Well, this may be a glib answer (my favorite kind), but it probably does it the same way it derives a class if you specify a parent. Isn't that how you'd do it if you were writing the compiler?
It's because all user defined types implicitly inherit from Object.
To say that the JVM "injects" properties or methods into the class makes it sound like it's something the compiler or runtime does after the fact, as though the .class file is different. Really, all that happens is that when the parser sees that you haven't included any base class with extends, it simply pretends you explicitly specified Object. From that point onward, the compiler treats it the same as if you'd typed it out yourself, and the JVM hasn't a clue what you did or didn't specify in the source code.

Categories

Resources