Forums

Reflection: I have missed somewhere?

General discussion about Cobra. Releases and general news will also be posted here.
Feel free to ask questions or just say "Hello".

Reflection: I have missed somewhere?

Postby arisawa » Wed Aug 26, 2009 12:18 pm

why not found Tests.AMethod ?
Code: Select all
use System.Reflection

class Prog
   var t as Type?
   cue init
      base.init
      it = Tests(3)
      .t = it.typeOf
      
   def main
      p = Prog()
      a = Tests(2)
      print a.aMethod(9)
      
      o1 as Object[] = Object[](1)
      obj as Object? = Activator.createInstance(.t, o1)
      
      o2 as Object[] = Object[](5)
      res = .t.invokeMember('AMethod', BindingFlags.Default | BindingFlags.InvokeMethod, nil, obj, o2) to int
      print .t.name, res


class Tests
   var n as int = 0
   var s as String?
   cue init(a as int)
      base.init
      .n = a
      
   def typeOf as System.Type
      return .getType
      
   def aMethod(m as int) as int
      return .n * m
      
   pro strN as String?
      get
         return .s
         
      set
         .s = value

Regards,
arisawa
 
Posts: 51

Re: Reflection: I have missed somewhere?

Postby Charles » Wed Aug 26, 2009 3:13 pm

These are just library issues. No problems with Cobra. First, the argument to "Object[](5)" is the length of the array. So you really want "Object[](1)" and then set the first value. Second, I had to remove BindingFlags.Default. This worked for me:
args = Object[](1)
args[0] = 5
res = .t.invokeMember('AMethod', BindingFlags.InvokeMethod, nil, obj, args) to int
trace obj, res

Note that you can also get this kind of thing done with much less code:
res = (obj to dynamic).aMethod(5)
trace obj, res

You can also skip the use of Activator.createInstance:
t = .t to dynamic
obj = t(5) # calling a dynamic value that happens to be a type, makes an object
res = obj.aMethod(5) # more dynamic binding
trace obj, res

In many cases, you can skip reflection and just use Cobra's dynamic type for smaller, cleaner code.
Charles
 
Posts: 2515
Location: Los Angeles, CA


Return to Discussion

Who is online

Users browsing this forum: No registered users and 81 guests