Reflection and private methods in gosu

926 views
Skip to first unread message

extenditus

unread,
Feb 18, 2013, 1:32:49 PM2/18/13
to gosu...@googlegroups.com
How can i invoke a private method in gosu from another class using reflection?

I am basically trying to do this

method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);

Any direction would help.
Thanks.


Carson Gross

unread,
Feb 18, 2013, 1:44:37 PM2/18/13
to gosu...@googlegroups.com
Here's an example:

var s = "This is a string"
var m = s.Class.getDeclaredMethod( "checkBounds", {byte[], int, int} )
m.Accessible = true
m.invoke( s, {s.Bytes, 0, 1} )

Cheers,
Carson
--
You received this message because you are subscribed to the Google Groups "gosu-lang" group.
To unsubscribe from this group and stop receiving emails from it, send an email to gosu-lang+...@googlegroups.com.
To post to this group, send email to gosu...@googlegroups.com.
Visit this group at http://groups.google.com/group/gosu-lang?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

extenditus

unread,
Feb 18, 2013, 3:00:39 PM2/18/13
to gosu...@googlegroups.com
 Thanks Carson.

 Is there a way to do the same thing from the TypeSystem.

e.g
  var s =""
  ( typeof s).<path to private method>

Carson Gross

unread,
Feb 18, 2013, 4:04:23 PM2/18/13
to gosu...@googlegroups.com
A little verbose, but it works:

uses gw.lang.reflect.IRelativeTypeInfo

var s = "This is a string"
var type = typeof s
var m = (type.TypeInfo as IRelativeTypeInfo).getMethod( type, "checkBounds", {byte[], int, int} )
m.CallHandler.handleCall( s, {s.Bytes, 0, 1} )

Depending on your version of Gosu, you may not need to cast to IRelativeTypeInfo to access the getMethod(IType, name, argTypes) method, I don't have access to the code base now, but I know there was talk about moving that method up to ITypeInfo at one point.

And, to be very safe, you probably want to test if the thing is an IRelativeTypeInfo using Gosu's handy-dandy auto-downcasting:

if( type.TypeInfo typeis IRelativeTypeInfo ) {
  var m = type.TypeInfo.getMethod( type, "checkBounds", {byte[], int, int} )
  m.CallHandler.handleCall( s, {s.Bytes, 0, 1} )
} else {
  var m = type.TypeInfo.getMethod( "checkBounds", {byte[], int, int} )
  m.CallHandler.handleCall( s, {s.Bytes, 0, 1} )
}

Cheers,
Carson

osagie uwaifo

unread,
Feb 18, 2013, 9:07:37 PM2/18/13
to gosu-lang

Thanks Carson! I will give that a try in the morning.

Reply all
Reply to author
Forward
0 new messages