Question

Its been one of those days can someone help me out with this.

I have 2 Stock Objects which I want to compare properties of at runtime. One instance is the cached instance, the other is a new stock instance which has just been delivered to my system, which may or may not equal the cached instance. See below where m is a method from the class Stock and stock is an instance of Stock

try {

// I want to compare these two objects, return type of m may vary
Object result = m.invoke(stock);
Object cacheResult = m.invoke(stockCache.get(ticker));

// The return type of m may vary but is known at runtime
Class returnType = m.getReturnType();

// I assume I need to cast before .equals() will work correctly
if(result.equals(cacheResult)) {
    // Will this work or do I need to cast
}

  }catch (Exception ex) {
 }

EDIT: For those who have asked about why I am using reflection, I am using the reverse ajax framework DWR and I am trying to map a html id property to my object properties, allowing me to annotate my properties with their associated HTML id value. When pushing the object to the UI this method will allow me to only push properties that have changed and not the whole object.

Was it helpful?

Solution

You shouldn't need to cast. Java will automatically choose the correct equals method. I recommend you debug that line to see what Class each object is.

OTHER TIPS

No, you dont need to cast. Normally, equals method looks like

@Override
public boolean equals(Object o){

   if (! o instance of ThisClass){
      return false;
   }

   //other equality tests based on members
 }

If your cache holds only one class-objects (i.e not caching derived classes), it should work. Looks like that you are storing Objects in your StockCache. Maybe that's a little too generic, and narrowing down to some base class (maybe StockClass) would be a better option. Then, your getter would be, defined in your cache class would be:

StockObject getStockObject(KeyType key);

In addition to this, reflection seems like an overkill (if you alredy have the objects you want to compare, why use reflection?)

Casting will not have any effect here. The result depends entirely on how the equals() method is implemented in the Stock class.

But why are you using reflection for this anyway? It's most likely not the right thing to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top