/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
package de.steamwar.persistent;
import lombok.experimental.UtilityClass;
@UtilityClass
public class Reflection {
public static class Field {
private final java.lang.reflect.Field f;
public Field(Class target, String name) {
try {
f = target.getDeclaredField(name);
f.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException("Cannot find field with name " + name, e);
}
}
public T get(C target) {
try {
return (T) f.get(target);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Cannot access reflection.", e);
}
}
public void set(C target, T value) {
try {
f.set(target, value);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Cannot access reflection.", e);
}
}
}
public static class Method {
private final java.lang.reflect.Method m;
public Method(Class clazz, String methodName, Class>... params) {
try {
m = clazz.getDeclaredMethod(methodName, params);
m.setAccessible(true);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Cannot find method with name " + methodName, e);
}
}
public Object invoke(C target, Object... arguments) {
try {
return m.invoke(target, arguments);
} catch (Exception e) {
throw new IllegalArgumentException("Cannot invoke method " + m, e);
}
}
}
}