IVR Avenger
IVR Avenger

Reputation: 15494

Determine if a class is a field on another class

I have a java class that looks like this:

public class MainClass {

  public static class InnerClass1 extends SomeClass {
    ...
  }

  public static class InnerClass2 extends SomeClass {
    ...
  }
}

At runtime, is there a way examine an object that's an instance of InnerClass1 and know that its a field on MainClass? I know I can add a static array to MainClass that contains a list of its SomeClass fields, but I'd like something that's a bit more programmatically dynamic. Something like this:

MainClass.InnerClass1 object1 = someKindOfFactory.getObject();
BigDecimal someNumber = new BigDecimal("45.77");

if (object1.comesFrom(MainClass.class)) {
  LOG.debug("Object is from MainClass");
} else {
  LOG.debug("Object comes from somewhere else");
}

if (someNumber.comesFrom(MainClass.class)) {
  LOG.debug("Object is from MainClass");
} else {
  LOG.debug("Object comes from somewhere else");
}

Results:

DEBUG: Object is from MainClass
DEBUG: Object comes from somewhere else 

Upvotes: 1

Views: 115

Answers (3)

Ian Roberts
Ian Roberts

Reputation: 122364

It's hard to tell exactly what you're trying to achieve but Class.getEnclosingClass() may help you here:

MainClass.InnerClass1 object1 = someKindOfFactory.getObject();
BigDecimal someNumber = new BigDecimal("45.77");

if (object1.getClass().getEnclosingClass() == MainClass.class) {
  LOG.debug("Object is from MainClass");
} else {
  LOG.debug("Object comes from somewhere else");
}

if (someNumber.getClass().getEnclosingClass() == MainClass.class) {
  LOG.debug("Object is from MainClass");
} else {
  LOG.debug("Object comes from somewhere else");
}

In this case object1.getClass().getEnclosingClass() == MainClass.class is true if object1 is an instance of InnerClass1 directly, but false if object1 is a subclass of InnerClass1 that is declared somewhere else.

Upvotes: 2

Hot Licks
Hot Licks

Reputation: 47729

If what you mean is to determine, at runtime, whether a given field is defined in the subclass or the superclass, you'd have to use getDeclaredFields on the Class object of the subclass and see if the field in question is listed. Of course, you first need to get the field name, and it's not obvious how you do that.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279980

When you create an object and hold a reference to it

Object obj = new Object();

you can pass around this reference pretty much anywhere you want, ie. assign it to a class field, use it as a method argument, etc. There's nothing linking it to a specific class field.

Similarly, an inner class has a reference to its outer class. However, you can have any number of inner class objects created. The outer class has no way of knowing how many or which they are (imagine the garbage collection nightmare).

Upvotes: 0

Related Questions