Skip to content

Instantly share code, notes, and snippets.

@hugithordarson
Created January 24, 2018 12:59
Show Gist options
  • Save hugithordarson/1b7ed95b7a57b83d89142ea722a3b544 to your computer and use it in GitHub Desktop.
Save hugithordarson/1b7ed95b7a57b83d89142ea722a3b544 to your computer and use it in GitHub Desktop.
package gardur.app;
import java.util.Optional;
import com.webobjects.foundation.NSKeyValueCoding;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;
public class AddOptionalSupportToKVC {
public static void register() {
ByteBuddyAgent.install();
new ByteBuddy()
.redefine( NSKeyValueCoding.DefaultImplementation.class )
.visit( Advice.to( KVCAdvisor.class )
.on( ElementMatchers.named( "valueForKey" ) ) )
.make()
.load(
NSKeyValueCoding.DefaultImplementation.class.getClassLoader(),
ClassReloadingStrategy.fromInstalledAgent() );
}
public static class KVCAdvisor {
@Advice.OnMethodExit
static void exit( @Advice.Return( readOnly = false ) Object returnValue ) throws Exception {
if( returnValue instanceof Optional ) {
if( ((Optional)returnValue).isPresent() ) {
returnValue = ((Optional)returnValue).get();
}
else {
returnValue = null;
}
}
}
}
public static class TestOptionalSupport {
public static void main( String argv[] ) {
AddOptionalSupportToKVC.register();
Object emptyResult = NSKeyValueCoding.DefaultImplementation.valueForKey( new TestOptionalSupport(), "emptyOptional" );
Object presentResult = NSKeyValueCoding.DefaultImplementation.valueForKey( new TestOptionalSupport(), "presentOptional" );
System.out.println( "emptyResult: " + emptyResult ); // This is null
System.out.println( "presentResult: " + presentResult ); // This is "I'm not empty!"
}
public Optional<String> emptyOptional() {
return Optional.empty();
}
public Optional<String> presentOptional() {
return Optional.of( "I'm not empty!" );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment