GetField.java
/***************************************************************************
Copyright 2013 Emily Estes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***************************************************************************/
package net.metanotion.util.reflect;
import java.lang.reflect.Field;
import net.metanotion.util.Dictionary;
import net.metanotion.util.types.ObjectP;
import net.metanotion.util.types.Parser;
/** A class that simplifies retrieving the value of a field from an object instance.
This class implements a dictionary where the "keys" are the objects which
have the field whose value is being retrieved.
*/
public final class GetField implements Dictionary {
private final Field f;
private final Parser p;
/** Create a new field "getter".
@param f The field this instance will look up.
*/
public GetField(Field f) { this(f, ObjectP.INSTANCE); }
/** Create a new field "getter".
@param f The field this instance will look up.
@param p The parser used to "translate" the field when it's value is being set.
*/
public GetField(Field f, Parser p) {
this.f = f;
this.p = p;
}
/** Retrieve the type of the field this instance retrieves.
@return The type of the field.
*/
public Class type() { return f.getType(); }
@Override public Object get(Object instance) {
try {
return f.get(instance);
} catch (IllegalAccessException iae) { throw new RuntimeException(iae); }
}
/** Set the value of the field on an object instance.
@param instance The instance to change the field value.
@param value The new value to change the instance's field to.
*/
public void set(Object instance, Object value) {
try {
f.set(instance, p.parse(value));
} catch (Exception e) { throw new RuntimeException(e); }
}
}