blob: 202af6f8915cdb7b64db0468b7a0f51dbccdf01a [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2021 Stephan Wahlbrink and others.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors:
# Stephan Wahlbrink <sw@wahlbrink.eu> - initial API and implementation
#=============================================================================*/
package org.eclipse.statet.rj.servi;
import static org.eclipse.statet.jcommons.lang.ObjectUtils.nonNullAssert;
import java.lang.reflect.Field;
import org.eclipse.statet.jcommons.lang.NonNullByDefault;
import org.eclipse.statet.jcommons.lang.Nullable;
@NonNullByDefault
public class Accessor {
private Class<?> clazz;
private final Object instance;
public Accessor(final Object instance, final Class<?> clazz) {
this.instance= nonNullAssert(instance);
this.clazz= nonNullAssert(clazz);
}
public Accessor(final Object instance, final String className, final ClassLoader classLoader) {
this.instance= nonNullAssert(instance);
try {
this.clazz= Class.forName(className, true, classLoader);
}
catch (ClassNotFoundException | ExceptionInInitializerError e) {
throw new RuntimeException(e);
}
}
public Field getField(final String fieldName) {
try {
final Field field= this.clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
}
catch (SecurityException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
public @Nullable Object getFieldObj(final String fieldName) {
try {
final Field field= getField(fieldName);
return field.get(this.instance);
}
catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}