import java.lang.invoke.CallSite;
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
class Ideone {
ISetter
<TestEntity, Long
> setter
= getSetter
(TestEntity.
class,
"id",
Long.
class);
TestEntity te = new TestEntity(10L);
System.
out.
println(te.
getId()); setter.set(te, 15L);
System.
out.
println(te.
getId()); }
public static <T, R
> ISetter
<T, R
> getSetter
(Class
<T
> clazz,
String fieldName, Class
<R
> fieldType
) throws Throwable {
MethodHandles.Lookup caller = MethodHandles.lookup();
MethodType setter = MethodType.methodType(void.class, fieldType);
MethodHandle target = caller.findVirtual(clazz, computeSetterName(fieldName), setter);
MethodType func = target.type();
CallSite site = LambdaMetafactory.metafactory(
caller,
"set",
MethodType.methodType(ISetter.class),
func.erase(),
target,
func
);
MethodHandle factory = site.getTarget();
ISetter<T, R> r = (ISetter<T, R>) factory.invoke();
return r;
}
return "set" + Character.
toUpperCase(name.
charAt(0)) + name.
substring(1); }
}
interface ISetter<T, R> {
void set(T object, R value);
}
class TestEntity {
public TestEntity
(Long id
) { this.id = id;
}
return id;
}
public void setId
(Long id
) { this.id = id;
}
}
aW1wb3J0IGphdmEubGFuZy5pbnZva2UuQ2FsbFNpdGU7CmltcG9ydCBqYXZhLmxhbmcuaW52b2tlLkxhbWJkYU1ldGFmYWN0b3J5OwppbXBvcnQgamF2YS5sYW5nLmludm9rZS5NZXRob2RIYW5kbGU7CmltcG9ydCBqYXZhLmxhbmcuaW52b2tlLk1ldGhvZEhhbmRsZXM7CmltcG9ydCBqYXZhLmxhbmcuaW52b2tlLk1ldGhvZFR5cGU7CgpjbGFzcyBJZGVvbmUgewoJCglwdWJsaWMgc3RhdGljIHZvaWQgbWFpbihTdHJpbmdbXSBhcmdzKSB0aHJvd3MgVGhyb3dhYmxlIHsKCQlJU2V0dGVyPFRlc3RFbnRpdHksIExvbmc+IHNldHRlciA9IGdldFNldHRlcihUZXN0RW50aXR5LmNsYXNzLC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