gpt4 book ai didi

dart - 获取所有具有注释的类的 ClassMirror 实例

转载 作者:行者123 更新时间:2023-12-03 03:13:25 26 4
gpt4 key购买 nike

我有这个注释

class Target{
final String value;
const Target(this.value);
}

以及用它注释的 2 个类

@Target("/313")
class c1{

}

@Target("/314")
class c2{

}

如何获取具有 Target 注释的类的 ClassMirror 实例列表?

基于所选的答案,即如果我知道我的类(class)存在于哪个图书馆

  var mirrorSystem = currentMirrorSystem();
var libraryMirror = mirrorSystem.findLibrary(#testlib);
for(ClassMirror classMirror in libraryMirror.declarations.values){
if(classMirror.metadata!=null){
for(var meta in classMirror.metadata){
if(meta.type == reflectClass(Path)){
print(classMirror.simpleName);
print(meta.getField(#value));
}
}
}
}

最佳答案

这将搜索当前隔离中的所有库,以查找使用 @Target('/313') 注释的类

@MirrorsUsed(metaTargets: Target) // might be necessary when you build this code to JavaScript
import 'dart:mirrors';

class Target {
final String id;
const Target(this.id);
}

@Target('/313')
class c1{

}

@Target('/314')
class c2{

}

@Target('/313')
@Target('/314')
class c3{

}

void main() {
MirrorSystem mirrorSystem = currentMirrorSystem();
mirrorSystem.libraries.forEach((lk, l) {
l.declarations.forEach((dk, d) {
if(d is ClassMirror) {
ClassMirror cm = d as ClassMirror;
cm.metadata.forEach((md) {
InstanceMirror metadata = md as InstanceMirror;
if(metadata.type == reflectClass(Target) && metadata.getField(#id).reflectee == '/313') {
print('found: ${cm.simpleName}');
}
});
}
});
});
}

found: Symbol("c3")
found: Symbol("c1")

关于dart - 获取所有具有注释的类的 ClassMirror 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24457283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com