如何找到所有装饰有某种装饰的班级? [英] How to find all classes decorated with a certain decoration?
问题描述
在Java中,我们可以使用类路径扫描"找到所有具有给定注释的类.
In Java we can find all classes that have a given annotation using "classpath scanning".
我们如何在TypeScript中做类似的事情?有没有办法找到所有装饰有装饰的班级?
How can we do something similar in TypeScript? Is there a way to find all classes decorated with some decoration?
推荐答案
下面是一个示例.它假定您有某种引用范围的方法. magical
类修饰器在要应用到的类上创建一个名为isMagical
的字符串属性,并将其值分配为"indeed".然后findMagicalInScope()
函数循环遍历指定范围内的属性(这就是所有类都在模块中的原因),并查看它们是否具有isMagical
属性.
Here's an example. It assumes you have some way of referencing the scope. The magical
class decorator creates a string property called isMagical
on the classes that it's applied to, and assigns the value of it as "indeed". Then the findMagicalInScope()
function loops through the properties on the specified scope (which is why the classes are all in a module) and sees if they have an isMagical
property.
module myContainer {
@magical
export class foo {
}
export class bar {
}
@magical
export class bas {
}
}
function magical(item: any) {
item.isMagical = "indeed";
}
function findMagicalInScope(theScope: any) {
for(let prop in theScope) {
if (theScope[prop]["isMagical"]) {
console.log(`Is ${prop} magical? ${theScope[prop]["isMagical"]}!`);
} else {
console.log(`${prop} is not magical. :-(`);
}
}
}
findMagicalInScope(myContainer);
在Node.js中运行时将生成此输出:
Will generate this output when run in Node.js:
Is foo magical? indeed!
bar is not magical. :-(
Is bas magical? indeed!
这篇关于如何找到所有装饰有某种装饰的班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!