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.
a source to share
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?)
a source to share