Java reflection get parent class

Java Reflection makes it easy to find fields, methods, and constructors in your Java classes. Most of the time a single class is all you need to look at. However, sometimes you need to navigate through a class hierarchy.

In this post, I’ll show you how to use Java Reflection to navigate class hierarchies. You’ll learn two techniques to do this, so you can pick the one that best suits your needs.

We’ll need an example to work with, so let’s use the Java Swing TextField class. Here’s the class hierarchy for JTextField from the Java API documentation.

Class JTextField

java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.text.JTextComponent javax.swing.JTextField

You can see that this class hierarchy is fairly deep. The Object class is at the top and JTextField is at the bottom. The other classes in between fill in the complete inheritance hierarchy.

Let’s write a Java Reflection program to navigate through this class hierarchy and print out the class and package names. We’ll write this program specifically for the JTextField class, but you should be able to easily adapt it to access class names in the inheritance hierarchy of any Java class.

Our program needs the getSuperclass() and getName() methods from the Java Reflection API. Both methods are called with Class objects.

The getName() method returns a string representing the Class object’s package and class name. The getSuperclass() method returns a Class object representing the parent or super class of the invoking Class object. Note that getSuperclass() returns null when called with a Class object representing the Object class, since Object has no parent.

Recursive Approach

Here’s the first technique for navigating class hierarchies.

public class SuperClasses < public static void main(String[] args) < showHierarchy(JTextField.class); >static void showHierarchy(Class c) < if (c.getSuperclass() == null) < System.out.println(c.getName()); return; >showHierarchy(c.getSuperclass()); System.out.println(c.getName()); > >

Interestingly, the showHierarchy() method has no loop as it navigates through the JTextField hierarchy. That’s because showHierarchy() is recursive. Do you see how this works?

Each call to showHierarchy() first invokes c.getSuperclass() at line 6 to fetch the parent of the current class. If this method does not return null, a recursive call to showHierarchy() is invoked with this parent class at line 10. Each recursion nests stack frames as it works its way up the inheritance tree.

Читайте также:  Язык программирования питон javascript

What makes the recursion finally stop? When we reach the Object class in the hierarchy, c.getSuperclass() returns null and the if statement at line 6 is true. At this point, the method calls c.getName() at line 7 to print the Object class before returning.

Next, each recursive invocation of showHierarchy() at line 10 returns as the nested stack frames unwind. This makes showHierarchy() display the current class name in the hierarchy at line 11.

Here’s the output from this program.

java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.text.JTextComponent javax.swing.JTextField

Note that the order of this output matches the order from the Java documentation page shown earlier.

Non Recursive Approach

Recursion is certainly an elegant solution to navigating class hierarchies, but recursive algorithms are not everyone’s cup of tea. Here’s a second version that doesn’t use recursion.

public class SuperClasses2 < public static void main(String[] args) < showHierarchy(JTextField.class); >static void showHierarchy(Class c) < ArrayList list = new ArrayList(); while (c != null) < list.add(0, c); // add to front c = c.getSuperclass(); >for (Class cls : list) System.out.println(cls.getName()); > >

You’ll note a few differences with this approach. First of all, an ArrayList stores Class objects. Second, two loops are necessary to display the class hierarchy in the correct order. Do you see why?

After creating an empty ArrayList of Class types at line 6, the method uses a while loop to add class objects to the ArrayList . Each call to c.getSuperclass() at line 9 fetches the parent of the current class after the current class is added to the front of the ArrayList in line 8. The while loop terminates when the Object class is reached for the current class.

The for loop calls getName() at line 12 to display the class and package names for each Class object in the ArrayList .

The output from this program is the same as the previous one.

java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.text.JTextComponent javax.swing.JTextField

Note that without an ArrayList to store Class objects, a single loop with successive calls to getSuperclass() would make the output of class names appear in the opposite order.

In this post, I showed two approaches that navigate class hierarchies with Java Reflection. The first technique was a recursive approach; the second technique was a non-recursive solution.

If you’d like to learn more about Java Reflection and other techniques like these, check out my JavaReflection LiveLesson.

Java Reflection Live Lesson

Источник

Java reflection mechanism demo (4)—Get the parent class and implemented interface of a class

1. Java reflection mechanism gets the parent class of a class

Use the getSuperClass() method in the Class class to get the parent class of a class

If this Class Said Object For a class, an interface, a basic type or void, null is returned. If this object represents an array class, it will return Object Category Class Object.

package com.aaron.reflect; public class Demo4 < public static void main(String[] args) < Classc = Integer.class; System.out.println("The parent class of Integer is: "+c.getSuperclass()); c = Number.class; System.out.println("The parent class of Number is: "+c.getSuperclass()); c = Object.class; System.out.println("The parent class of Object is: "+c.getSuperclass()); > >
The parent class of Integer is: class java.lang.Number The parent class of Number is: class java.lang.Object The parent class of Object is: null

Since Java does not have multiple inheritance, a class can only have one parent class at most, so the return type is not an array.

2. The Java reflection mechanism returns an interface implemented by a class

When we develop an interface and use a class to implement it, we see a class and we know what interface it implements, but when the machine itself gets a class, we don’t know what the interface it implements is like. Through the reflection mechanism, the Class object of the interface implemented by a certain class can be obtained, so that the internal structure of this interface can be explored.

A simple Demo is given in this article.

First, the definition of the interface is as follows;

package com.aaron.reflect; public interface Animal

Then, define a class to implement this interface

package com.aaron.reflect; import java.util.jar.Attributes.Name; public class Dog implements Animal < public final static String name = "dog"; @Override public String sayHello(String str) < return String.format("%s says : %s", this.name, str); >>

There is only one method in both the interface and the implementation class.

The code of the test class is as follows:

package com.aaron.reflect; public class Demo3 < public static void main(String[] args) < Classc = Dog.class;//Get the Class object corresponding to Dog Class interfaces[] = c.getInterfaces();//Get all the interfaces implemented by Dog for (Class inte: interfaces) > >
Dog implements the interface: interface com.aaron.reflect.Animal

Of course, Java does not have multiple inheritance, but it can implement multiple interfaces, so an array is returned here.

In the array obtained by Class[] getInterfaces(), The order of interface objects is consistent with the order of interface names in the implements clause of the class represented by this object 。

Источник

java reflection to invoke parent class method

send pies

posted 14 years ago

  • Report post to moderator
  • In the parent class, I have a public method, then in the child class, I try to access it using java reflection, it doesn’t work.

    send pies

    posted 14 years ago

  • Report post to moderator
  • Hi
    I am able to access the parent methods also in the child using reflection

    Can you elaborate more on what are you trying to do.

    send pies

    posted 14 years ago

  • Report post to moderator
  • Reflection is definitely not a beginner’s subject, so I’ll move the discussion to a more appropriate forum. Also, please note that ItDoesntWorkIsUseless. If you told us what you tried, and what exactly did or did not happen, we’d be in a much better position to help.

    Sheriff

    Chrome

    send pies

    posted 14 years ago

  • Report post to moderator
  • Which method are you using to get the method?

    getDeclaredXXX only returns members actually declared in that class; public methods and fields of the parent class are not found.

    getXXX only returns public members in that class, also those declared in the parent class (except when overridden / hidden). Non-public members are not found.

    SCJP 1.4 — SCJP 6 — SCWCD 5 — OCEEJBD 6 — OCEJPAD 6
    How To Ask Questions How To Answer Questions

    send pies

    posted 14 years ago

  • Report post to moderator
  • I wrote it’s now. don’t know if its works.

    Each of their nuggets of wisdom contracted to a sound bite: Joshua Bloch: Write Lots of Code; Chet Haase: Don’t Put Your Entire Application in One Method; Masood Mortazavi: Start Simple and Keep Learning; Cay Horstmann: First, Don’t Panic

    send pies

    posted 14 years ago

  • Report post to moderator
  • I wrote it’s now. don’t know if its works.

    And if you want access and invoke the private Methods you only need add this line before «return m;»

    Each of their nuggets of wisdom contracted to a sound bite: Joshua Bloch: Write Lots of Code; Chet Haase: Don’t Put Your Entire Application in One Method; Masood Mortazavi: Start Simple and Keep Learning; Cay Horstmann: First, Don’t Panic

    Sheriff

    Chrome

    send pies

    posted 14 years ago

  • Report post to moderator
  • Marky Vasconcellos wrote: I wrote it’s now. don’t know if its works.

    That solution would work for all methods, not only public ones. There is one «but» though: getMethod and getDeclaredMethod never return null, but throw a NoSuchMethodException instead. So your code would be this:

    Of course you can wrap the NoSuchFieldException in a RuntimeException if you don’t want the checked exception:

    Just be careful — your method only looks for methods without a parameter.

    Now, as I’ve said before, if you only need to look for public methods, it’s much simpler:

    SCJP 1.4 — SCJP 6 — SCWCD 5 — OCEEJBD 6 — OCEJPAD 6
    How To Ask Questions How To Answer Questions

    Источник

    Оцените статью