使用镜像,我如何获得对类的方法的引用? [英] Using mirrors, how can I get a reference to a class's method?

查看:123
本文介绍了使用镜像,我如何获得对类的方法的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类 Foo 的实例,我想获取以某种方式注释的所有方法的列表。我想要一个方法本身的引用,所以我不是每次都使用反射来调用方法,只是为了第一次抓住它的参考。

Say I have an instance of a class Foo, and I want to grab a list of all of its methods that are annotated a certain way. I want to have a reference to the method itself, so I'm not looking to use reflection to invoke the method each time, just to grab a reference to it the first time.

换句话说,我想做这样的反射:

In other words, I want to do the reflection equivalent of this:

class Foo {
  a() {print("a");}
}

void main() {
  var f = new Foo();
  var x = f.a; // Need reflective way of doing this
  x(); // prints "a"
}



我试过使用 InstanceMirror#getField ,但方法不被认为是字段,所以没有工作。任何想法?

I have tried using InstanceMirror#getField, but methods are not considered fields so that didn't work. Any ideas?

推荐答案

至于我理解Dart中的反射,没有办法得到实际的方法。 (我很高兴地删除这个答案,如果有人来,并显示如何做。)

As far as I understand reflection in Dart, there's no way to get the actual method as you wish to. (I'll very happily delete this answer if someone comes along and shows how to do that.)

最好的我可以想出来改善一些你可能不喜欢使用反射调用方法是这样的:

The best I can come up with to ameliorate some of what you probably don't like about using reflection to invoke the method is this:

import 'dart:mirrors';

class Foo {
  a() {print("a");}
}

void main() {
  var f = new Foo();

  final fMirror = reflect(f);
  final aSym = new Symbol('a');
  final x = () => fMirror.invoke(aSym, []);

  x(); // prints "a"
}

再次,我知道这不是你'

Again, I know that's not quite what you're looking for, but I believe it's as close as you can get.

注意: getField 调用getter并返回结果 - 如果getter实现为方法,实际上很好。它在这里不适合你,而是因为你想不到的原因。

Side note: getField invokes the getter and returns the result -- it's actually fine if the getter is implemented as a method. It doesn't work for you here, but for a different reason than you thought.

这篇关于使用镜像,我如何获得对类的方法的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆