Java Reflection Equal Question

This was one of those days when someone can help me with this.

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

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 asked a question about why I am using reflection, I am using the reverse AJAX DWR framework and I am trying to map the html id property to my object properties, which allows me to annotate my properties with their associated HTML id. When clicking an object on the UI, this method allows me to change only the properties that have changed, not the entire object.

+1


a source to share


4 answers


You don't have to quit. Java will automatically pick the correct method equals

. I recommend that you debug this line to see what is Class

for each object.



+7


a source


No, you don't have to quit. Usually the 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 only contains one class object (i.e. does not cache derived classes) then it should work. It looks like you are storing objects in your StockCache. Maybe this is too general and narrowing down to some base class (maybe StockClass) would be a better option. Then your receiver will be defined in your cache class:



StockObject getStockObject(KeyType key);

      

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

+3


a source


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

But why do you think about it that way? This is most likely not the case.

+2


a source


+1


a source







All Articles