Related
I want to return two objects from a Java method and was wondering what could be a good way of doing so?
The possible ways I can think of are: return a HashMap (since the two Objects are related) or return an ArrayList of Object objects.
To be more precise, the two objects I want to return are (a) List of objects and (b) comma separated names of the same.
I want to return these two Objects from one method because I dont want to iterate through the list of objects to get the comma separated names (which I can do in the same loop in this method).
Somehow, returning a HashMap does not look a very elegant way of doing so.
If you want to return two objects you usually want to return a single object that encapsulates the two objects instead.
You could return a List of NamedObject objects like this:
public class NamedObject<T> {
public final String name;
public final T object;
public NamedObject(String name, T object) {
this.name = name;
this.object = object;
}
}
Then you can easily return a List<NamedObject<WhateverTypeYouWant>>.
Also: Why would you want to return a comma-separated list of names instead of a List<String>? Or better yet, return a Map<String,TheObjectType> with the keys being the names and the values the objects (unless your objects have specified order, in which case a NavigableMap might be what you want.
If you know you are going to return two objects, you can also use a generic pair:
public class Pair<A,B> {
public final A a;
public final B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
};
Edit A more fully formed implementation of the above:
package util;
public class Pair<A,B> {
public static <P, Q> Pair<P, Q> makePair(P p, Q q) {
return new Pair<P, Q>(p, q);
}
public final A a;
public final B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + ((b == null) ? 0 : b.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
#SuppressWarnings("rawtypes")
Pair other = (Pair) obj;
if (a == null) {
if (other.a != null) {
return false;
}
} else if (!a.equals(other.a)) {
return false;
}
if (b == null) {
if (other.b != null) {
return false;
}
} else if (!b.equals(other.b)) {
return false;
}
return true;
}
public boolean isInstance(Class<?> classA, Class<?> classB) {
return classA.isInstance(a) && classB.isInstance(b);
}
#SuppressWarnings("unchecked")
public static <P, Q> Pair<P, Q> cast(Pair<?, ?> pair, Class<P> pClass, Class<Q> qClass) {
if (pair.isInstance(pClass, qClass)) {
return (Pair<P, Q>) pair;
}
throw new ClassCastException();
}
}
Notes, mainly around rustiness with Java & generics:
both a and b are immutable.
makePair static method helps you with boiler plate typing, which the diamond operator in Java 7 will make less annoying. There's some work to make this really nice re: generics, but it should be ok-ish now. (c.f. PECS)
hashcode and equals are generated by eclipse.
the compile time casting in the cast method is ok, but doesn't seem quite right.
I'm not sure if the wildcards in isInstance are necessary.
I've just written this in response to comments, for illustration purposes only.
In the event the method you're calling is private, or called from one location, try
return new Object[]{value1, value2};
The caller looks like:
Object[] temp=myMethod(parameters);
Type1 value1=(Type1)temp[0]; //For code clarity: temp[0] is not descriptive
Type2 value2=(Type2)temp[1];
The Pair example by David Hanak has no syntactic benefit, and is limited to two values.
return new Pair<Type1,Type2>(value1, value2);
And the caller looks like:
Pair<Type1, Type2> temp=myMethod(parameters);
Type1 value1=temp.a; //For code clarity: temp.a is not descriptive
Type2 value2=temp.b;
You may use any of following ways:
private static final int RETURN_COUNT = 2;
private static final int VALUE_A = 0;
private static final int VALUE_B = 1;
private static final String A = "a";
private static final String B = "b";
1) Using Array
private static String[] methodWithArrayResult() {
//...
return new String[]{"valueA", "valueB"};
}
private static void usingArrayResultTest() {
String[] result = methodWithArrayResult();
System.out.println();
System.out.println("A = " + result[VALUE_A]);
System.out.println("B = " + result[VALUE_B]);
}
2) Using ArrayList
private static List<String> methodWithListResult() {
//...
return Arrays.asList("valueA", "valueB");
}
private static void usingListResultTest() {
List<String> result = methodWithListResult();
System.out.println();
System.out.println("A = " + result.get(VALUE_A));
System.out.println("B = " + result.get(VALUE_B));
}
3) Using HashMap
private static Map<String, String> methodWithMapResult() {
Map<String, String> result = new HashMap<>(RETURN_COUNT);
result.put(A, "valueA");
result.put(B, "valueB");
//...
return result;
}
private static void usingMapResultTest() {
Map<String, String> result = methodWithMapResult();
System.out.println();
System.out.println("A = " + result.get(A));
System.out.println("B = " + result.get(B));
}
4) Using your custom container class
private static class MyContainer<M,N> {
private final M first;
private final N second;
public MyContainer(M first, N second) {
this.first = first;
this.second = second;
}
public M getFirst() {
return first;
}
public N getSecond() {
return second;
}
// + hashcode, equals, toString if need
}
private static MyContainer<String, String> methodWithContainerResult() {
//...
return new MyContainer("valueA", "valueB");
}
private static void usingContainerResultTest() {
MyContainer<String, String> result = methodWithContainerResult();
System.out.println();
System.out.println("A = " + result.getFirst());
System.out.println("B = " + result.getSecond());
}
5) Using AbstractMap.simpleEntry
private static AbstractMap.SimpleEntry<String, String> methodWithAbstractMapSimpleEntryResult() {
//...
return new AbstractMap.SimpleEntry<>("valueA", "valueB");
}
private static void usingAbstractMapSimpleResultTest() {
AbstractMap.SimpleEntry<String, String> result = methodWithAbstractMapSimpleEntryResult();
System.out.println();
System.out.println("A = " + result.getKey());
System.out.println("B = " + result.getValue());
}
6) Using Pair of Apache Commons
private static Pair<String, String> methodWithPairResult() {
//...
return new ImmutablePair<>("valueA", "valueB");
}
private static void usingPairResultTest() {
Pair<String, String> result = methodWithPairResult();
System.out.println();
System.out.println("A = " + result.getKey());
System.out.println("B = " + result.getValue());
}
I almost always end up defining n-Tuple classes when I code in Java. For instance:
public class Tuple2<T1,T2> {
private T1 f1;
private T2 f2;
public Tuple2(T1 f1, T2 f2) {
this.f1 = f1; this.f2 = f2;
}
public T1 getF1() {return f1;}
public T2 getF2() {return f2;}
}
I know it's a bit ugly, but it works, and you just have to define your tuple types once. Tuples are something Java really lacks.
EDIT: David Hanak's example is more elegant, as it avoids defining getters and still keeps the object immutable.
Before Java 5, I would kind of agree that the Map solution isn't ideal. It wouldn't give you compile time type checking so can cause issues at runtime. However, with Java 5, we have Generic Types.
So your method could look like this:
public Map<String, MyType> doStuff();
MyType of course being the type of object you are returning.
Basically I think that returning a Map is the right solution in this case because that's exactly what you want to return - a mapping of a string to an object.
Apache Commons has tuple and triple for this:
ImmutablePair<L,R> An immutable pair consisting of two Object
elements.
ImmutableTriple<L,M,R> An immutable triple consisting of
three Object elements.
MutablePair<L,R> A mutable pair consisting of
two Object elements.
MutableTriple<L,M,R> A mutable triple
consisting of three Object elements.
Pair<L,R> A pair consisting of
two elements.
Triple<L,M,R> A triple consisting of three elements.
Source: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html
Alternatively, in situations where I want to return a number of things from a method I will sometimes use a callback mechanism instead of a container. This works very well in situations where I cannot specify ahead of time just how many objects will be generated.
With your particular problem, it would look something like this:
public class ResultsConsumer implements ResultsGenerator.ResultsCallback
{
public void handleResult( String name, Object value )
{
...
}
}
public class ResultsGenerator
{
public interface ResultsCallback
{
void handleResult( String aName, Object aValue );
}
public void generateResults( ResultsGenerator.ResultsCallback aCallback )
{
Object value = null;
String name = null;
...
aCallback.handleResult( name, value );
}
}
While in your case, the comment may be a good way to go, in Android, you can use Pair . Simply
return new Pair<>(yourList, yourCommaSeparatedValues);
Use of following Entry object
Example :
public Entry<A,B> methodname(arg)
{
.......
return new AbstractMap.simpleEntry<A,B>(instanceOfA,instanceOfB);
}
Regarding the issue about multiple return values in general I usually use a small helper class that wraps a single return value and is passed as parameter to the method:
public class ReturnParameter<T> {
private T value;
public ReturnParameter() { this.value = null; }
public ReturnParameter(T initialValue) { this.value = initialValue; }
public void set(T value) { this.value = value; }
public T get() { return this.value; }
}
(for primitive datatypes I use minor variations to directly store the value)
A method that wants to return multiple values would then be declared as follows:
public void methodThatReturnsTwoValues(ReturnParameter<ClassA> nameForFirstValueToReturn, ReturnParameter<ClassB> nameForSecondValueToReturn) {
//...
nameForFirstValueToReturn.set("...");
nameForSecondValueToReturn.set("...");
//...
}
Maybe the major drawback is that the caller has to prepare the return objects in advance in case he wants to use them (and the method should check for null pointers)
ReturnParameter<ClassA> nameForFirstValue = new ReturnParameter<ClassA>();
ReturnParameter<ClassB> nameForSecondValue = new ReturnParameter<ClassB>();
methodThatReturnsTwoValues(nameForFirstValue, nameForSecondValue);
Advantages (in comparison to other solutions proposed):
You do not have to create a special class declaration for individual methods and its return types
The parameters get a name and therefore are easier to differentiate when looking at the method signature
Type safety for each parameter
All possible solutions will be a kludge (like container objects, your HashMap idea, “multiple return values” as realized via arrays). I recommend regenerating the comma-separated list from the returned List. The code will end up being a lot cleaner.
Keep it simple and create a class for multiple result situation. This example accepts an ArrayList and a message text from a databasehelper getInfo.
Where you call the routine that returns multiple values you code:
multResult res = mydb.getInfo();
In the routine getInfo you code:
ArrayList<String> list= new ArrayList<String>();
add values to the list...
return new multResult("the message", list);
and define a class multResult with:
public class multResult {
public String message; // or create a getter if you don't like public
public ArrayList<String> list;
multResult(String m, ArrayList<String> l){
message = m;
list= l;
}
}
As I see it there are really three choices here and the solution depends on the context. You can choose to implement the construction of the name in the method that produces the list. This is the choice you've chosen, but I don't think it is the best one. You are creating a coupling in the producer method to the consuming method that doesn't need to exist. Other callers may not need the extra information and you would be calculating extra information for these callers.
Alternatively, you could have the calling method calculate the name. If there is only one caller that needs this information, you can stop there. You have no extra dependencies and while there is a little extra calculation involved, you've avoided making your construction method too specific. This is a good trade-off.
Lastly, you could have the list itself be responsible for creating the name. This is the route I would go if the calculation needs to be done by more than one caller. I think this puts the responsibility for the creation of the names with the class that is most closely related to the objects themselves.
In the latter case, my solution would be to create a specialized List class that returns a comma-separated string of the names of objects that it contains. Make the class smart enough that it constructs the name string on the fly as objects are added and removed from it. Then return an instance of this list and call the name generation method as needed. Although it may be almost as efficient (and simpler) to simply delay calculation of the names until the first time the method is called and store it then (lazy loading). If you add/remove an object, you need only remove the calculated value and have it get recalculated on the next call.
Can do some thing like a tuple in dynamic language (Python)
public class Tuple {
private Object[] multiReturns;
private Tuple(Object... multiReturns) {
this.multiReturns = multiReturns;
}
public static Tuple _t(Object... multiReturns){
return new Tuple(multiReturns);
}
public <T> T at(int index, Class<T> someClass) {
return someClass.cast(multiReturns[index]);
}
}
and use like this
public Tuple returnMultiValues(){
return Tuple._t(new ArrayList(),new HashMap())
}
Tuple t = returnMultiValues();
ArrayList list = t.at(0,ArrayList.class);
I followed a similar approach than the described in the other answers with a few tweaks based on the requirement I had, basically I created the following classes(Just in case, everything is Java):
public class Pair<L, R> {
final L left;
final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public <T> T get(Class<T> param) {
return (T) (param == this.left.getClass() ? this.left : this.right);
}
public static <L, R> Pair<L, R> of(L left, R right) {
return new Pair<L, R>(left, right);
}
}
Then, my requirement was simple, in the repository Class that reaches the DB, for the Get Methods than retrieve data from the DB, I need to check if it failed or succeed, then, if succeed, I needed to play with the returning list, if failed, stop the execution and notify the error.
So, for example, my methods are like this:
public Pair<ResultMessage, List<Customer>> getCustomers() {
List<Customer> list = new ArrayList<Customer>();
try {
/*
* Do some work to get the list of Customers from the DB
* */
} catch (SQLException e) {
return Pair.of(
new ResultMessage(e.getErrorCode(), e.getMessage()), // Left
null); // Right
}
return Pair.of(
new ResultMessage(0, "SUCCESS"), // Left
list); // Right
}
Where ResultMessage is just a class with two fields (code/message) and Customer is any class with a bunch of fields that comes from the DB.
Then, to check the result I just do this:
void doSomething(){
Pair<ResultMessage, List<Customer>> customerResult = _repository.getCustomers();
if (customerResult.get(ResultMessage.class).getCode() == 0) {
List<Customer> listOfCustomers = customerResult.get(List.class);
System.out.println("do SOMETHING with the list ;) ");
}else {
System.out.println("Raised Error... do nothing!");
}
}
In C++ (STL) there is a pair class for bundling two objects. In Java Generics a pair class isn't available, although there is some demand for it. You could easily implement it yourself though.
I agree however with some other answers that if you need to return two or more objects from a method, it would be better to encapsulate them in a class.
Why not create a WhateverFunctionResult object that contains your results, and the logic required to parse these results, iterate over then etc. It seems to me that either:
These results objects are intimately tied together/related and belong together, or:
they are unrelated, in which case your function isn't well defined in terms of what it's trying to do (i.e. doing two different things)
I see this sort of issue crop up again and again. Don't be afraid to create your own container/result classes that contain the data and the associated functionality to handle this. If you simply pass the stuff around in a HashMap or similar, then your clients have to pull this map apart and grok the contents each time they want to use the results.
public class MultipleReturnValues {
public MultipleReturnValues() {
}
public static void functionWithSeveralReturnValues(final String[] returnValues) {
returnValues[0] = "return value 1";
returnValues[1] = "return value 2";
}
public static void main(String[] args) {
String[] returnValues = new String[2];
functionWithSeveralReturnValues(returnValues);
System.out.println("returnValues[0] = " + returnValues[0]);
System.out.println("returnValues[1] = " + returnValues[1]);
}
}
This is not exactly answering the question, but since every of the solution given here has some drawbacks, I suggest to try to refactor your code a little bit so you need to return only one value.
Case one.
You need something inside as well as outside of your method. Why not calculate it outside and pass it to the method?
Instead of:
[thingA, thingB] = createThings(...); // just a conceptual syntax of method returning two values, not valid in Java
Try:
thingA = createThingA(...);
thingB = createThingB(thingA, ...);
This should cover most of your needs, since in most situations one value is created before the other and you can split creating them in two methods. The drawback is that method createThingsB has an extra parameter comparing to createThings, and possibly you are passing exactly the same list of parameters twice to different methods.
Case two.
Most obvious solution ever and a simplified version of case one. It's not always possible, but maybe both of the values can be created independently of each other?
Instead of:
[thingA, thingB] = createThings(...); // see above
Try:
thingA = createThingA(...);
thingB = createThingB(...);
To make it more useful, these two methods can share some common logic:
public ThingA createThingA(...) {
doCommonThings(); // common logic
// create thing A
}
public ThingB createThingB(...) {
doCommonThings(); // common logic
// create thing B
}
Pass a list to your method and populate it, then return the String with the names, like this:
public String buildList(List<?> list) {
list.add(1);
list.add(2);
list.add(3);
return "something,something,something,dark side";
}
Then call it like this:
List<?> values = new ArrayList<?>();
String names = buildList(values);
You can utilize a HashMap<String, Object> as follows
public HashMap<String, Object> yourMethod()
{
.... different logic here
HashMap<String, Object> returnHashMap = new HashMap<String, Object>();
returnHashMap.put("objectA", objectAValue);
returnHashMap.put("myString", myStringValue);
returnHashMap.put("myBoolean", myBooleanValue);
return returnHashMap;
}
Then when calling the method in a different scope, you can cast each object back to its initial type:
// call the method
HashMap<String, Object> resultMap = yourMethod();
// fetch the results and cast them
ObjectA objectA = (ObjectA) resultMap.get("objectA");
String myString = (String) resultMap.get("myString");
Boolean myBoolean = (Boolean) resultMap.get("myBoolean");
I noticed there is no no-custom class, n-length, no-cast, type-safe answers yet to returning multiple values.
Here is my go:
import java.util.Objects;
public final class NTuple<V, T extends NTuple<?, ?>> {
private final V value;
private final T next;
private NTuple(V value, T next) {
this.value = value;
this.next = next;
}
public static <V> NTuple<V, ?> of(V value) {
return new NTuple<>(value, null);
}
public static <V, T extends NTuple<?, ?>> NTuple<V, T> of(V value, T next) {
return new NTuple<>(value, next);
}
public V value() {
return value;
}
public T next() {
return next;
}
public static <V> V unpack0(NTuple<V, ?> tuple) {
return Objects.requireNonNull(tuple, "0").value();
}
public static <V, T extends NTuple<V, ?>> V unpack1(NTuple<?, T> tuple) {
NTuple<?, T> tuple0 = Objects.requireNonNull(tuple, "0");
NTuple<V, ?> tuple1 = Objects.requireNonNull(tuple0.next(), "1");
return tuple1.value();
}
public static <V, T extends NTuple<?, NTuple<V, ?>>> V unpack2(NTuple<?, T> tuple) {
NTuple<?, T> tuple0 = Objects.requireNonNull(tuple, "0");
NTuple<?, NTuple<V, ?>> tuple1 = Objects.requireNonNull(tuple0.next(), "1");
NTuple<V, ?> tuple2 = Objects.requireNonNull(tuple1.next(), "2");
return tuple2.value();
}
}
Sample use:
public static void main(String[] args) {
// pre-java 10 without lombok - use lombok's var or java 10's var if you can
NTuple<String, NTuple<Integer, NTuple<Integer, ?>>> multiple = wordCount("hello world");
String original = NTuple.unpack0(multiple);
Integer wordCount = NTuple.unpack1(multiple);
Integer characterCount = NTuple.unpack2(multiple);
System.out.println(original + ": " + wordCount + " words " + characterCount + " chars");
}
private static NTuple<String, NTuple<Integer, NTuple<Integer, ?>>> wordCount(String s) {
int nWords = s.split(" ").length;
int nChars = s.length();
return NTuple.of(s, NTuple.of(nWords, NTuple.of(nChars)));
}
Pros:
no-custom container class - no need to write a class just for a return type
n-length - can handle any number of return values
no-cast - no need to cast from Object
type-safe - the types are checked via Java's generics
Cons:
inefficient for large numbers of return values
according to my experience with python's multiple return values, this should not happen in practice
heavy type declarations
can be alleviated by lombok/Java 10 var
In C, you would do it by passing pointers to placeholders for the results as arguments:
void getShoeAndWaistSizes(int *shoeSize, int *waistSize) {
*shoeSize = 36;
*waistSize = 45;
}
...
int shoeSize, waistSize;
getShoeAndWaistSize(&shoeSize, &waistSize);
int i = shoeSize + waistSize;
Let's try something similar, in Java.
void getShoeAndWaistSizes(List<Integer> shoeSize, List<Integer> waistSize) {
shoeSize.add(36);
waistSize.add(45);
}
...
List<Integer> shoeSize = new List<>();
List<Integer> waistSize = new List<>();
getShoeAndWaistSizes(shoeSize, waistSize);
int i = shoeSize.get(0) + waistSize.get(0);
PASS A HASH INTO THE METHOD AND POPULATE IT......
public void buildResponse(String data, Map response);
I've got a simple Method that returns me always "-undefined-".
public static String getStereoType(Class<?> clazz) {
String result = "-undefined-";
if (clazz.isEnum()) {
result = "enum";
} else if (clazz.isInterface()) {
result = "interface";
} else if (clazz.isLocalClass() || clazz.isMemberClass()) {
result = "class";
}
return result;
}
When I call this Method with Object.class or Long.class always is the result "-undefined-".
List<Class<?>> superClazzes = ClassUtil.getSuperClazzList(clazz);
for (Class<?> c: superClazzess){
String stereoType = ClassUtil.getStereoType(c.getClass());
}
public static List<Class<?>> getSuperClazzList(Class<?> clazz) {
List<Class<?>> resultList = new ArrayList<Class<?>>();
Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {
resultList.add(superClass);
resultList.addAll(getSuperClazzList(superClass));
}
return resultList;
}
What are you trying to get? So what are the possible stereo types you need? What I know of is:
Enum
Interface
Primitive (e.g. double, but not Double)
Class (everything else!)
And from the class API I can find that you might also differ between:
annotation (actual an interface in java)
synthetic (I'm not sure what this is)
local (defined inside a method)
But they might not be interesting for ULM diagrams at all.
Implementation of toString() from the JVM Class is:
public String toString() {
return (isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) + getName();
}
This might give you some hint as well.
Hope it helps.
Edit: This should do the job:
public static String getStereoType(Class<?> clazz) {
String result = "class";
if (clazz.isEnum()) {
result = "enum";
} else if (clazz.isInterface()) {
result = "interface";
}
else if (clazz.isPrimitive()) {
result = "primitive";
}
return result;
}
To answer the question in your title, isLocalClass() does not always return false: it returns true for types declared within a method. Similarly, isMemberClass() returns true for types declared within another type.
Consider:
public class Outer {
interface MemberClass {}
public static void main(String[] args) {
class LocalClass {}
System.out.printf(
"%s/%s%n",
LocalClass.class.isLocalClass(),
LocalClass.class.isMemberClass()
);
System.out.printf(
"%s/%s%n",
MemberClass.class.isLocalClass(),
MemberClass.class.isMemberClass()
);
}
}
This code, when executed, prints out true/false followed by false/true. Together, they only account for types which are defined within another class, or within a method. Neither strictly depends on the target type being a class as opposed to an interface or enum, so you cannot use it to filter that way.
See #Tarion's excellent answer for the approach you should be taking (and accept his answer, as it more completely solves your problem).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Anything wrong with instanceof checks here?
I have this code
public static int getNumberOfOwned(Player owner, String type){
int count = 0;
for (Field f: board.fieldList)
if (type == "Shipping" && f instanceof Shipping)
if (((Shipping)f).getOwnedBy() == owner)
count++;
else if (type == "Brewery" && f instanceof Brewery)
if (((Brewery)f).getOwnedBy() == owner)
count++;
return count;
}
I don't think this is very elegant and future proof. How can i avoid those instanceof operators.
You can always use an enum, and use a method on Field which returns the type. Here I'll go a little further and surmise that you do not want to update the count for certain types, so the enum is also "adorned" with a boolean expressing that:
enum FieldType {
SHIPPING(true),
BREWERY(true),
NOTME(false);
private final boolean countUpdate;
FieldType(boolean countUpdate) { this.countUpdate = countUpdate; }
public boolean mustUpdateCount() { return countUpdate; }
};
abstract class Field {
protected final FieldType type;
protected Field(FieldType type) { this.type = type; }
public final FieldType getType() { return type; }
public final boolean mustUpdateCount() { return type.mustUpdateCount(); }
}
class Brewery implements Field {
Brewery() {
super(BREWERY);
}
}
and in your code:
FieldType expectedType = Enum.valueOf(type.toUpperCase());
for (Field f: board.fieldlist) {
if (field.getType() != expectedType)
continue;
if (!f.getOwnedBy().equals(owner))
continue;
// Correct type, owned by the correct guy:
// check that we must update; if so, update
if (expectedType.mustUpdateCount())
count++;
}
Since Shipping and Brewery are derived from Field, Field could provide a getter that tells you its type, something like getFieldType(). When Shipping or Brewery are instantiated, they set the appropriate value, or you make getFieldType() abstract and have Shipping and Brewery implement them.
Pass Shipping.class or Brewery.class to your function instead of a string representing the class and check that your Field belongs to that class:
public static int getNumberOfOwned(Player owner, Class<? extends Field> type){
int count = 0;
for (Field f: board.fieldList) {
if (type.isInstance(f) && f.getOwnedBy() == owner) {
count++;
}
}
return count;
}
The best solution would be to use the visitor pattern for this problem, you can look it up here: Visitor pattern
At least it's the object oriented way of handling the problem, but it certainly needs more coding than your current solution.
Add an "isType(String type)" method to Field. For that matter, add "isOwnedBy(String owner)" to Field as well.
for (Field f: board.fieldList)
if (f.isType(type) && f.isOwnedBy(owner))
count++;
return count;
first of all be advice you are using the "==" operator to test the equality of objects, this is most of the the times wrong, and definitely wrong in this case :)
If you want to determine if an object is of an particular type you could use the instanceof operator, see if they have the same class reference (here you could use the "==" operator) or try a cast and check for an exception, the last option is more of a fantasy because in the real world you should not try this.
I am not quite sure what you are trying to do, but you could definitely tailor your objects to avoid the instanceof/class/cast stuff, something like:
class Foxtrot implements Sub {
private SubType type = SubType.ATACK;
public SubType getType() {
return type;
}
}
interface Sub {
enum SubType{ ATACK, BOOMER }
public SubType getType();
}
And you can treat object as implementations of the Sub interface and check with their getType() method what kind they are, it should pretty much work.
You should rewrite this code
1)
class Field
add method getType();
2) code:
public static int getNumberOfOwned(Player owner, String type){
int count = 0;
for (Field f: board.fieldList){
if (f.getType.equals(type)&& f.getOwnedBy().equesl(owner))
count++;
}
return count;
}
Make string getTypeString() a property of Field, and avoid having a bunch of if statements (check type.equals(f.getTypeString())) Make getOwnedBy a property of Field, and don't use a cast. (fields that don't have owners can return null)
I have a question of using switch case for instanceof object:
For example: my problem can be reproduced in Java:
if(this instanceof A)
doA();
else if(this instanceof B)
doB();
else if(this instanceof C)
doC():
How would it be implemented using switch...case?
This is a typical scenario where subtype polymorphism helps. Do the following
interface I {
void do();
}
class A implements I { void do() { doA() } ... }
class B implements I { void do() { doB() } ... }
class C implements I { void do() { doC() } ... }
Then you can simply call do() on this.
If you are not free to change A, B, and C, you could apply the visitor pattern to achieve the same.
if you absolutely cannot code to an interface, then you could use an enum as an intermediary:
public A() {
CLAZZ z = CLAZZ.valueOf(this.getClass().getSimpleName());
switch (z) {
case A:
doA();
break;
case B:
doB();
break;
case C:
doC();
break;
}
}
enum CLAZZ {
A,B,C;
}
Create a Map where the key is Class<?> and the value is an expression (lambda or similar). Consider:
Map<Class,Runnable> doByClass = new HashMap<>();
doByClass.put(Foo.class, () -> doAClosure(this));
doByClass.put(Bar.class, this::doBMethod);
doByClass.put(Baz.class, new MyCRunnable());
// of course, refactor this to only initialize once
doByClass.get(getClass()).run();
If you need checked exceptions than implement a FunctionalInterface that throws the Exception and use that instead of Runnable.
Here's a real-word before-and-after showing how this approach can simplify code.
The code before refactoring to a map:
private Object unmarshall(
final Property<?> property, final Object configValue ) {
final Object result;
final String value = configValue.toString();
if( property instanceof SimpleDoubleProperty ) {
result = Double.parseDouble( value );
}
else if( property instanceof SimpleFloatProperty ) {
result = Float.parseFloat( value );
}
else if( property instanceof SimpleBooleanProperty ) {
result = Boolean.parseBoolean( value );
}
else if( property instanceof SimpleFileProperty ) {
result = new File( value );
}
else {
result = value;
}
return result;
}
The code after refactoring to a map:
private final Map<Class<?>, Function<String, Object>> UNMARSHALL =
Map.of(
SimpleBooleanProperty.class, Boolean::parseBoolean,
SimpleDoubleProperty.class, Double::parseDouble,
SimpleFloatProperty.class, Float::parseFloat,
SimpleFileProperty.class, File::new
);
private Object unmarshall(
final Property<?> property, final Object configValue ) {
return UNMARSHALL
.getOrDefault( property.getClass(), ( v ) -> v )
.apply( configValue.toString() );
}
This avoids repetition, eliminates nearly all branching statements, and simplifies maintenance.
Java now allows you to switch in the manner of the OP. They call it Pattern Matching for switch. It was released as a preview feature of Java 17. The example given in the JEP is
String formatted;
switch (obj) {
case Integer i : formatted = String.format ( "int %d", i); break;
case Byte b : formatted = String.format ( "byte %d", b); break;
case Long l : formatted = String.format ( "long %d", l); break;
case Double d : formatted = String.format ( "double %f", d); break;
case String s : formatted = String.format ( "String %s", s); break
default: formatted = obj.toString();
}
or using their lambda syntax and returning a value
String formatted = switch (obj) {
case Integer i -> String.format ( "int %d", i )
case Byte b -> String.format ( "byte %d", b );
case Long l -> String.format ( "long %d", l );
case Double d -> String.format ( "double %f", d );
case String s -> String.format ( "String %s", s );
default -> obj.toString();
};
either way they've been doing cool stuff with switches.
Just in case if someone will read it:
The BEST solution in java is :
public enum Action {
a{
void doAction(...){
// some code
}
},
b{
void doAction(...){
// some code
}
},
c{
void doAction(...){
// some code
}
};
abstract void doAction (...);
}
The GREAT benefits of such pattern are:
You just do it like (NO switches at all):
void someFunction ( Action action ) {
action.doAction(...);
}
In case if you add new Action called "d" you MUST imlement doAction(...) method
NOTE: This pattern is described in Joshua's Bloch "Effective Java (2nd Edition)"
You can't. The switch statement can only contain case statements which are compile time constants and which evaluate to an integer (Up to Java 6 and a string in Java 7).
What you are looking for is called "pattern matching" in functional programming.
See also Avoiding instanceof in Java
As discussed in the top answers, the traditional OOP approach is to use polymorphism instead of switch. There is even a well documented refactoring pattern for this trick: Replace Conditional with Polymorphism. Whenever I reach for this approach, I like to also implement a Null object to provide the default behaviour.
Starting with Java 8, we can use lambdas and generics to give us something functional programmers are very familiar with: pattern matching. It's not a core language feature but the VAVR Library - formerly Javaslang library provides one implementation. Example from the docs:
Match.ofType(Number.class)
.caze((Integer i) -> i)
.caze((String s) -> new BigDecimal(s))
.orElse(() -> -1)
.apply(1.0d); // result: -1
It's not the most natural paradigm in the Java world so use it with caution. While the generic methods will save you from having to typecast the matched value, we're missing a standard way to decompose the matched object as with Scala's case classes for example.
Unfortunately, it is not possible out of the box since the switch-case statement expects a constant expression. To overcome this, one way would be to use enum values with the class names e.g.
public enum MyEnum {
A(A.class.getName()),
B(B.class.getName()),
C(C.class.getName());
private String refClassname;
private static final Map<String, MyEnum> ENUM_MAP;
MyEnum (String refClassname) {
this.refClassname = refClassname;
}
static {
Map<String, MyEnum> map = new ConcurrentHashMap<String, MyEnum>();
for (MyEnum instance : MyEnum.values()) {
map.put(instance.refClassname, instance);
}
ENUM_MAP = Collections.unmodifiableMap(map);
}
public static MyEnum get(String name) {
return ENUM_MAP.get(name);
}
}
With that is is possible to use the switch statement like this
MyEnum type = MyEnum.get(clazz.getName());
switch (type) {
case A:
... // it's A class
case B:
... // it's B class
case C:
... // it's C class
}
I know this is very late but for future readers ...
Beware of the approaches above that are based only on the name of the class of A, B, C ... :
Unless you can guarantee that A, B, C ... (all subclasses or implementers of Base) are final then subclasses of A, B, C ... will not be dealt with.
Even though the if, elseif, elseif .. approach is slower for large number of subclasses/implementers, it is more accurate.
java 7+
public <T> T process(Object model) {
switch (model.getClass().getSimpleName()) {
case "Trade":
return processTrade((Trade) model);
case "InsuranceTransaction":
return processInsuranceTransaction((InsuranceTransaction) model);
case "CashTransaction":
return processCashTransaction((CashTransaction) model);
case "CardTransaction":
return processCardTransaction((CardTransaction) model);
case "TransferTransaction":
return processTransferTransaction((TransferTransaction) model);
case "ClientAccount":
return processAccount((ClientAccount) model);
...
default:
throw new IllegalArgumentException(model.getClass().getSimpleName());
}
}
You can be even faster by for omitting string manipulation inside getSimpleName by for introducing constants and using full class name:
public static final TRADE = Trade.class.getName();
...
switch (model.getClass().getName()) {
case TRADE:
Nope, there is no way to do this. What you might want to do is however to consider Polymorphism as a way to handle these kind of problems.
Using switch statements like this is not the object oriented way. You should instead use the power of polymorphism. Simply write
this.do()
Having previously set up a base class:
abstract class Base {
abstract void do();
...
}
which is the base class for A, B and C:
class A extends Base {
void do() { this.doA() }
}
class B extends Base {
void do() { this.doB() }
}
class C extends Base {
void do() { this.doC() }
}
You can't a switch only works with the byte, short, char, int, String and enumerated types (and the object versions of the primitives, it also depends on your java version, Strings can be switched on in java 7)
I personally like the following Java 1.8 code:
mySwitch("YY")
.myCase("AA", (o) -> {
System.out.println(o+"aa");
})
.myCase("BB", (o) -> {
System.out.println(o+"bb");
})
.myCase("YY", (o) -> {
System.out.println(o+"yy");
})
.myCase("ZZ", (o) -> {
System.out.println(o+"zz");
});
Will output:
YYyy
The sample code uses Strings but you can use any object type, including Class. e.g. .myCase(this.getClass(), (o) -> ...
Needs the following snippet:
public Case mySwitch(Object reference) {
return new Case(reference);
}
public class Case {
private Object reference;
public Case(Object reference) {
this.reference = reference;
}
public Case myCase(Object b, OnMatchDo task) {
if (reference.equals(b)) {
task.task(reference);
}
return this;
}
}
public interface OnMatchDo {
public void task(Object o);
}
If you can manipulate the common interface, you could do add in an enum and have each class return a unique value. You won't need instanceof or a visitor pattern.
For me, the logic needed to be in the written in the switch statement, not the object itself. This was my solution:
ClassA, ClassB, and ClassC implement CommonClass
Interface:
public interface CommonClass {
MyEnum getEnumType();
}
Enum:
public enum MyEnum {
ClassA(0), ClassB(1), ClassC(2);
private int value;
private MyEnum(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
Impl:
...
switch(obj.getEnumType())
{
case MyEnum.ClassA:
ClassA classA = (ClassA) obj;
break;
case MyEnum.ClassB:
ClassB classB = (ClassB) obj;
break;
case MyEnum.ClassC:
ClassC classC = (ClassC) obj;
break;
}
...
If you are on java 7, you can put string values for the enum and the switch case block will still work.
How about this ?
switch (this.name)
{
case "A":
doA();
break;
case "B":
doB();
break;
case "C":
doC();
break;
default:
console.log('Undefined instance');
}
I think there are reasons to use a switch statement. If you are using xText generated Code perhaps. Or another kind of EMF generated classes.
instance.getClass().getName();
returns a String of the Class Implementation Name. i.e:
org.eclipse.emf.ecore.util.EcoreUtil
instance.getClass().getSimpleName();
returns the simple represenation i.e:
EcoreUtil
If you need to "switch" thru the class type of "this" object, this answer is the best https://stackoverflow.com/a/5579385/2078368
But if you need to apply "switch" to any other variable. I would suggest another solution. Define following interface:
public interface ClassTypeInterface {
public String getType();
}
Implement this interface in every class you want to "switch". Example:
public class A extends Something implements ClassTypeInterface {
public final static String TYPE = "A";
#Override
public String getType() {
return TYPE;
}
}
After that you can use it in following way:
switch (var.getType()) {
case A.TYPE: {
break;
}
case B.TYPE: {
break;
}
...
}
The only thing you should care about - keep the "types" unique across all the classes implementing the ClassTypeInterface. It's not a big problem, because in case of any intersection you receive a compile-time error for the "switch-case" statement.
Create an Enum with Class names.
public enum ClassNameEnum {
A, B, C
}
Find the Class name of the object.
Write a switch case over the enum.
private void switchByClassType(Object obj) {
ClassNameEnum className = ClassNameEnum.valueOf(obj.getClass().getSimpleName());
switch (className) {
case A:
doA();
break;
case B:
doB();
break;
case C:
doC();
break;
}
}
}
Hope this helps.
Here's a functional way of accomplishing it in Java 8 using http://www.vavr.io/
import static io.vavr.API.*;
import static io.vavr.Predicates.instanceOf;
public Throwable liftRootCause(final Throwable throwable) {
return Match(throwable).of(
Case($(instanceOf(CompletionException.class)), Throwable::getCause),
Case($(instanceOf(ExecutionException.class)), Throwable::getCause),
Case($(), th -> th)
);
}
While it is not possible to write a switch statement, it is possible to branch out to specific processing for each given type. One way of doing this is to use standard double dispatch mechanism. An example where we want to "switch" based on type is Jersey Exception mapper where we need to map multitude of exceptions to error responses. While for this specific case there is probably a better way (i.e. using a polymorphic method that translates each exception to an error response), using double dispatch mechanism is still useful and practical.
interface Processable {
<R> R process(final Processor<R> processor);
}
interface Processor<R> {
R process(final A a);
R process(final B b);
R process(final C c);
// for each type of Processable
...
}
class A implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class B implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class C implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
Then where ever the "switch" is needed, you can do it as follows:
public class LogProcessor implements Processor<String> {
private static final Logger log = Logger.for(LogProcessor.class);
public void logIt(final Processable base) {
log.info("Logging for type {}", process(base));
}
// Processor methods, these are basically the effective "case" statements
String process(final A a) {
return "Stringifying A";
}
String process(final B b) {
return "Stringifying B";
}
String process(final C c) {
return "Stringifying C";
}
}
Starting from Java 17 you can use pattern matching for switch expressions (preview feature) JEP-406.
public void doAction(Object o) {
return switch (o) {
case A a -> doA(a);
case B b -> doB(b);
case C c -> doC(c);
default -> log.warn("Unrecognized type of {}", o);
};
}
Guard pattern is also available:
public void doAction(Object o) {
return switch (o) {
case String s && !s.isBlank() -> handle(s);
};
}
You need to enable preview features to use it: java --enable-preview
In Java 19 recent release this has been very easy and useful :
Create interface and have method called makesomenoise() which accepts animal parameter.
void makeSomeNoise (Animal animal) {
switch (animal) {
case Dog dog → dog.bark();
case Cat catcat.meow();
default throw new RuntimeException ("WTH is it???");
}
}
there is an even simpler way of emulating a switch structure that uses instanceof, you do this by creating a code block in your method and naming it with a label. Then you use if structures to emulate the case statements. If a case is true then you use the break LABEL_NAME to get out of your makeshift switch structure.
DEFINE_TYPE:
{
if (a instanceof x){
//do something
break DEFINE_TYPE;
}
if (a instanceof y){
//do something
break DEFINE_TYPE;
}
if (a instanceof z){
// do something
break DEFINE_TYPE;
}
}
The Eclipse Modelling Framework has an interesting idea that also considers inheritance. The basic concept is defined in the Switch interface: switching is done by invoking the doSwitch method.
What is really interesting is the implementation. For each type of interest, a
public T caseXXXX(XXXX object);
method must be implemented (with a default implementation returning null). The doSwitch implementation will attempt to call al the caseXXX methods on the object for all its type hierarchy. Something in the lines of:
BaseType baseType = (BaseType)object;
T result = caseBaseType(eAttribute);
if (result == null) result = caseSuperType1(baseType);
if (result == null) result = caseSuperType2(baseType);
if (result == null) result = caseSuperType3(baseType);
if (result == null) result = caseSuperType4(baseType);
if (result == null) result = defaultCase(object);
return result;
The actual framework uses an integer id for each class, so the logic is actually a pure switch:
public T doSwitch(Object object) {
return doSwitch(object.class(), eObject);
}
protected T doSwitch(Class clazz, Object object) {
return doSwitch(getClassifierID(clazz), object);
}
protected T doSwitch(int classifierID, Object theObject) {
switch (classifierID) {
case MyClasses.BASETYPE:
{
BaseType baseType = (BaseType)object;
...
return result;
}
case MyClasses.TYPE1:
{
...
}
...
You can look at a complete implementation of the ECoreSwitch to get a better idea.
If you want to avoid the verbosity of if(){} else if{}, you may consider switching this single file to kotlin and use the switch-like when expression in combination with is operator.
In any case Kotlin and java files can co-exist in a project and result in a jar that can run in JVM.
when (this) { //switch-like statement in kotlin supporting class-pattern-matching and smart casts via `is` operator.
is A -> doA()
is B -> doB()
is C -> doC()
}
I need to compare dozens of fields in two objects (instances of the same class), and do some logging and updating in case there are differences. Meta code could look something like this:
if (a.getfield1 != b.getfield1)
log(a.getfield1 is different than b.getfield1)
b.field1 = a.field1
if (a.getfield2!= b.getfield2)
log(a.getfield2 is different than b.getfield2)
b.field2 = a.field2
...
if (a.getfieldn!= b.getfieldn)
log(a.getfieldn is different than b.getfieldn)
b.fieldn = a.fieldn
The code with all the comparisons is very terse, and I would like to somehow make it more compact. It would be nice if I could have a method which would take as a parameter method calls to setter and getter, and call this for all fields, but unfortunately this is not possible with java.
I have come up with three options, each which their own drawbacks.
1. Use reflection API to find out getters and setters
Ugly and could cause run time errors in case names of fields change
2. Change fields to public and manipulate them directly without using getters and setters
Ugly as well and would expose implementation of the class to external world
3. Have the containing class (entity) do the comparison, update changed fields and return log message
Entity should not take part in business logic
All fields are String type, and I can modify code of the class owning the fields if required.
EDIT: There are some fields in the class which must not be compared.
Use Annotations.
If you mark the fields that you need to compare (no matter if they are private, you still don't lose the encapsulation, and then get those fields and compare them. It could be as follows:
In the Class that need to be compared:
#ComparableField
private String field1;
#ComparableField
private String field2;
private String field_nocomparable;
And in the external class:
public <T> void compare(T t, T t2) throws IllegalArgumentException,
IllegalAccessException {
Field[] fields = t.getClass().getDeclaredFields();
if (fields != null) {
for (Field field : fields) {
if (field.isAnnotationPresent(ComparableField.class)) {
field.setAccessible(true);
if ( (field.get(t)).equals(field.get(t2)) )
System.out.println("equals");
field.setAccessible(false);
}
}
}
}
The code is not tested, but let me know if helps.
The JavaBeans API is intended to help with introspection. It has been around in one form or another since Java version 1.2 and has been pretty usable since version 1.4.
Demo code that compares a list of properties in two beans:
public static void compareBeans(PrintStream log,
Object bean1, Object bean2, String... propertyNames)
throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
Set<String> names = new HashSet<String>(Arrays
.asList(propertyNames));
BeanInfo beanInfo = Introspector.getBeanInfo(bean1
.getClass());
for (PropertyDescriptor prop : beanInfo
.getPropertyDescriptors()) {
if (names.remove(prop.getName())) {
Method getter = prop.getReadMethod();
Object value1 = getter.invoke(bean1);
Object value2 = getter.invoke(bean2);
if (value1 == value2
|| (value1 != null && value1.equals(value2))) {
continue;
}
log.format("%s: %s is different than %s%n", prop
.getName(), "" + value1, "" + value2);
Method setter = prop.getWriteMethod();
setter.invoke(bean2, value2);
}
}
if (names.size() > 0) {
throw new IllegalArgumentException("" + names);
}
}
Sample invocation:
compareBeans(System.out, bean1, bean2, "foo", "bar");
If you go the annotations route, consider dumping reflection and generating the comparison code with a compile-time annotation processor or some other code generator.
I would go for option 1, but I would use getClass().getDeclaredFields() to access the fields instead of using the names.
public void compareAndUpdate(MyClass other) throws IllegalAccessException {
for (Field field : getClass().getDeclaredFields()) {
if (field.getType() == String.class) {
Object thisValue = field.get(this);
Object otherValue = field.get(other);
// if necessary check for null
if (!thisValue.equals(otherValue)) {
log(field.getName() + ": " + thisValue + " <> " + otherValue);
field.set(other, thisValue);
}
}
}
}
There are some restrictions here (if I'm right):
The compare method has to be implemented in the same class (in my opinion it should - regardless of its implementation) not in an external one.
Just the fields from this class are used, not the one's from a superclass.
Handling of IllegalAccessException necessary (I just throw it in the example above).
This is probably not too nice either, but it's far less evil (IMHO) than either of the two alternatives you've proposed.
How about providing a single getter/setter pair that takes a numeric index field and then have getter/setter dereference the index field to the relevant member variable?
i.e.:
public class MyClass {
public void setMember(int index, String value) {
switch (index) {
...
}
}
public String getMember(int index) {
...
}
static public String getMemberName(int index) {
...
}
}
And then in your external class:
public void compareAndUpdate(MyClass a, MyClass b) {
for (int i = 0; i < a.getMemberCount(); ++i) {
String sa = a.getMember();
String sb = b.getMember();
if (!sa.equals(sb)) {
Log.v("compare", a.getMemberName(i));
b.setMember(i, sa);
}
}
}
This at least allows you to keep all of the important logic in the class that's being examined.
While option 1 may be ugly, it will get the job done. Option 2 is even uglier, and opens your code to vulnerabilities you can't imagine. Even if you eventually rule out option 1, I pray you keep your existing code and not go for option 2.
Having said this, you can use reflection to get a list of the field names of the class, if you don't want to pass this as a static list to the method. Assuming you want to compare all fields, you can then dynamically create the comparisons, in a loop.
If this isn't the case, and the strings you compare are only some of the fields, you can examine the fields further and isolate only those that are of type String, and then proceed to compare.
Hope this helps,
Yuval =8-)
since
All fields are String type, and I can modify code of the class owning the fields if required.
you could try this class:
public class BigEntity {
private final Map<String, String> data;
public LongEntity() {
data = new HashMap<String, String>();
}
public String getFIELD1() {
return data.get(FIELD1);
}
public String getFIELD2() {
return data.get(FIELD2);
}
/* blah blah */
public void cloneAndLogDiffs(BigEntity other) {
for (String field : fields) {
String a = this.get(field);
String b = other.get(field);
if (!a.equals(b)) {
System.out.println("diff " + field);
other.set(field, this.get(field));
}
}
}
private String get(String field) {
String value = data.get(field);
if (value == null) {
value = "";
}
return value;
}
private void set(String field, String value) {
data.put(field, value);
}
#Override
public String toString() {
return data.toString();
}
magic code:
private static final String FIELD1 = "field1";
private static final String FIELD2 = "field2";
private static final String FIELD3 = "field3";
private static final String FIELD4 = "field4";
private static final String FIELDN = "fieldN";
private static final List<String> fields;
static {
fields = new LinkedList<String>();
for (Field field : LongEntity.class.getDeclaredFields()) {
if (field.getType() != String.class) {
continue;
}
if (!Modifier.isStatic(field.getModifiers())) {
continue;
}
fields.add(field.getName().toLowerCase());
}
}
this class has several advantages:
reflects once, at class loading
it is very simply adding new fields, just add new static field (a better solution here
is using Annotations: in the case you care using reflection works also java 1.4)
you could refactor this class in an abstract class, all derived class just get both
data and cloneAndLogDiffs()
the external interface is typesafe (you could also easily impose immutability)
no setAccessible calls: this method is problematic sometimes
A broad thought:
Create a new class whose object takes the following parameters: the first class to compare, the second class to compare, and a lists of getter & setter method names for the objects, where only methods of interest are included.
You can query with reflection the object's class, and from that its available methods. Assuming each getter method in the parameter list is included in the available methods for the class, you should be able to call the method to get the value for comparison.
Roughly sketched out something like (apologies if it isn't super-perfect... not my primary language):
public class MyComparator
{
//NOTE: Class a is the one that will get the value if different
//NOTE: getters and setters arrays must correspond exactly in this example
public static void CompareMyStuff(Object a, Object b, String[] getters, String[] setters)
{
Class a_class = a.getClass();
Class b_class = b.getClass();
//the GetNamesFrom... static methods are defined elsewhere in this class
String[] a_method_names = GetNamesFromMethods(a_class.getMethods());
String[] b_method_names = GetNamesFromMethods(b_class.getMethods());
String[] a_field_names = GetNamesFromFields(a_class.getFields());
//for relative brevity...
Class[] empty_class_arr = new Class[] {};
Object[] empty_obj_arr = new Object[] {};
for (int i = 0; i < getters.length; i++)
{
String getter_name = getter[i];
String setter_name = setter[i];
//NOTE: the ArrayContainsString static method defined elsewhere...
//ensure all matches up well...
if (ArrayContainsString(a_method_names, getter_name) &&
ArrayContainsString(b_method_names, getter_name) &&
ArrayContainsString(a_field_names, setter_name)
{
//get the values from the getter methods
String val_a = a_class.getMethod(getter_name, empty_class_arr).invoke(a, empty_obj_arr);
String val_b = b_class.getMethod(getter_name, empty_class_arr).invoke(b, empty_obj_arr);
if (val_a != val_b)
{
//LOG HERE
//set the value
a_class.getField(setter_name).set(a, val_b);
}
}
else
{
//do something here - bad names for getters and/or setters
}
}
}
}
You say you presently have getters and setters for all these fields? Okay, then change the underlying data from a bunch of individual fields to an array. Change all the getters and setters to access the array. I'd create constant tags for the indexes rather than using numbers for long-term maintainability. Also create a parallel array of flags indicating which fields should be processed. Then create a generic getter/setter pair that use an index, as well as a getter for the compare flag. Something like this:
public class SomeClass
{
final static int NUM_VALUES=3;
final static int FOO=0, BAR=1, PLUGH=2;
String[] values=new String[NUM_VALUES];
static boolean[] wantCompared={true, false, true};
public String getFoo()
{
return values[FOO];
}
public void setFoo(String foo)
{
values[FOO]=foo;
}
... etc ...
public int getValueCount()
{
return NUM_VALUES;
}
public String getValue(int x)
{
return values[x];
}
public void setValue(int x, String value)
{
values[x]=value;
}
public boolean getWantCompared(int x)
{
return wantCompared[x];
}
}
public class CompareClass
{
public void compare(SomeClass sc1, SomeClass sc2)
{
int z=sc1.getValueCount();
for (int x=0;x<z;++x)
{
if (!sc1.getWantCompared[x])
continue;
String sc1Value=sc1.getValue(x);
String sc2Value=sc2.getValue(x);
if (!sc1Value.equals(sc2Value)
{
writeLog(x, sc1Value, sc2Value);
sc2.setValue(x, sc1Value);
}
}
}
}
I just wrote this off the top of my head, I haven't tested it, so their may be bugs in the code, but I think the concept should work.
As you already have getters and setters, any other code using this class should continue to work unchanged. If there is no other code using this class, then throw away the existing getters and setters and just do everything with the array.
I would also propose a similar solution to the one by Alnitak.
If the fields need to be iterated when comparing, why not dispense with the separate fields, and put the data into an array, a HashMap or something similar that is appropriate.
Then you can access them programmatically, compare them etc. If different fields need to be treated & compared in different ways, you could create approriate helper classes for the values, which implement an interface.
Then you could just do
valueMap.get("myobject").compareAndChange(valueMap.get("myotherobject")
or something along those lines...