- Notifications
You must be signed in to change notification settings - Fork 0
Java Reflection
Some people think java reflection is cool (they are mistaken, it is not is a pain), where possible avoid using it at all costs, unfortunately some of the processing guys seem to think it is cool, so they have contaminated the processing api with it. Fortunately there are often ways to avoid it (and sometimes come up with something that is more appropriate for use in a ruby environment). One such example is the thread convenience method of processing, that relies on reflection to allow you to pass a function to a thread.
thread("someFunction");
voidsomeFunction(){
dostuff..
}In ruby-processing we have overridden the thread convenience method to be much more ruby like (in keeping with ruby Thread, whilst actually using a java thread under hood) to take a block.
threaddosomestuff..
endActually we don't really need this convenience function in ruby-processing we've just overridden it to prevent any confusion, it is just as easy to use the existing Thread syntax...
Thread.newdosomestuff..
endAnother example where reflection gets pressed into action is the recommended way that you "registerMethods" with the processing Applet from a processing library, this is done using reflection as follows
publicBasicLibrary(PAppletparent) {
this.parent = parent;
parent.registerMethod("dispose", this);
}
publicvoiddispose() {
// Anything in here will be called automatically when // the parent sketch shuts down. For instance, this might// shut down a thread used by this library.
}You have to go through hoops to replicate this in ruby but it can be done:-
require'jruby/core_ext'classTestRegisterattr_reader:parentdefinitializeparent@parent=parentregister=parent.java_method:registerMethod,[Java::JavaLang::String,java.lang.Object]register.call(:draw,self)register.call(:pre,self)enddefpreputs"before draw"parent.background(100)enddefdrawputs"at begin draw"parent.fill(200,100)parent.ellipse(100,100,60,60)endendcls=TestRegister.become_java!The magic in the last line ensures that the TestRegister class becomes java, so that when you pass self, it is a java.lang.Object. And believe it or not this actually works see following sketch:-
load"./register.rb"defsetupsize200,200fred=TestRegister.newselfno_loopenddefdrawfill(0,0,200)ellipse(120,120,60,60)endAnyone who can get registerMethod("mouseEvent") or registerMethod("keyEvent") to actually work in ruby-processing might find this useful, please be kind enough to let us know how you got it to work!!! Yet another daft usage of reflection in vanilla processing in is in the callback for selectInput, it really is dreadful stuff (it is what you might call optimistic programming at best), you quickly get into the realms of exceptions that you can't handle (java.lang.reflect.InvocationCallbackException) all to produce some poxy convenience method...
