gpt4 book ai didi

scala - Scala反射,查找并实例化具有给定注释的所有类

转载 作者:行者123 更新时间:2023-12-04 08:19:45 26 4
gpt4 key购买 nike

我想使用反射在运行时查找具有给定批注的所有类,但是我无法在Scala中弄清楚该如何做。然后,我想获取注释的值,并动态实例化映射到关联注释的值的每个带注释的类的实例。

这是我想做的:

package problem
import scala.reflect.runtime._

object Program {

case class Foo (key: String) extends scala.annotation.StaticAnnotation

case class Bar ()
@Foo ("x")
case class Bar0 extends Bar
@Foo ("y")
case class Bar1 extends Bar
@Foo ("z")
case class Bar2 extends Bar

def main (args : Array[String]): Unit = {

// I want to use reflection to build
// the following dynamically at run time:
// val whatIWant: Map [String, Bar] =
// Map("x" -> Bar0 (), "y" -> Bar1 (), "z" -> Bar2 ())
// (it's a map of attribute key -> an instance
// of the type that has that attribute with that key)
val whatIWant: Map [String, Bar] = ?
}
}


并且,希望能够更好地解释自己,这就是我将如何解决C#中的问题。

using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;

namespace scalaproblem
{
public class FooAttribute : Attribute
{
public FooAttribute (String s) { Id = s; }
public String Id { get; private set; }
}

public abstract class Bar {}

[Foo ("x")]
public class Bar0: Bar {}

[Foo ("y")]
public class Bar1: Bar {}

[Foo ("z")]
public class Bar2: Bar {}

public static class AttributeExtensions
{
public static TValue GetAttributeValue<TAttribute, TValue>(this Type type, Func<TAttribute, TValue> valueSelector)
where TAttribute : Attribute
{
var att = type.GetCustomAttributes (typeof(TAttribute), true).FirstOrDefault() as TAttribute;
if (att != null)
return valueSelector(att);
return default(TValue);
}
}

public static class Program
{
public static void Main ()
{
var assembly = Assembly.GetExecutingAssembly ();
Dictionary<String, Bar> whatIWant = assembly
.GetTypes()
.Where (t => Attribute.IsDefined (t, typeof(FooAttribute)))
.ToDictionary (t => t.GetAttributeValue((FooAttribute f) => f.Id), t => Activator.CreateInstance (t) as Bar);

whatIWant.Keys.ToList().ForEach (k => Console.WriteLine (k + " ~ " + whatIWant [k]));
}
}
}

最佳答案

最实用的答案是使用reflections library扫描具有特定批注的所有类的类路径(或其子集)。然后,您可以使用Java Reflection API或Scala Reflection实例化它们。

(请注意,这不是100%可靠的,因为允许类加载器是动态的,因此可能有一个类不会在扫描中显示。但是在实践中,对于“正常”用例(即从普通的jar文件),效果很好)

关于scala - Scala反射,查找并实例化具有给定注释的所有类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28214579/

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