我有一个实现接口的类。该类有一个私有的 double 字段field1,它使用@Valuespring 注释从应用程序属性中读取值。
我正在开发测试,我需要从该类中填充该字段。为了实现这一点,我正在使用:
ReflectionTestUtils.setField(Class.class, "field1", value, double.class);
Run Code Online (Sandbox Code Playgroud)
我总是收到空指针异常,但调试日志显示:
DEBUG org.springframework.test.util.ReflectionTestUtils - Setting field 'field1' of type [double] on target object [null] or target class [class com.a.b.c.Class] to value [value].
有人知道如何使用反射为该字段设置值,或者如何为该类字段填充一些值?我没有该类的任何实例,但有接口。
我试图动态地使用反射做一个OrderBy是否给定的sortColumn(串)为空或不是,一ThenBy对sortColumn价值和ThenBy对硬编码列。像这样:
if (!String.IsNullOrEmpty(sortColumn)) {
var descending = sortDirection == "desc";
views = views.AsQueryable()
.OrderByNull<ToDoView>(sortColumn, true) // extension method
.OrderBy<ToDoView>(sortColumn, descending, true) // extension method
.ThenBy(v => v.summary ?? v.description).ToList();
}
Run Code Online (Sandbox Code Playgroud)
使用其他 SO 答案,我能够使OrderBy扩展方法起作用:
public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source,
string orderByProperty, bool desc, bool thenBy = false) {
string command = desc ? "OrderByDescending" : "OrderBy";
if (thenBy)
command = desc ? "ThenByDescending" : "ThenBy";
var type = …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试Class.getMethod用作吸气剂。
我尝试使用这种方法:
//This works fine
Class<?> c = Class.forName("Cat");
//This is not working
Cat cat = c.getMethod("getCat");
Run Code Online (Sandbox Code Playgroud)
但它不起作用。
在带有 Scala 的代码库中工作,它希望您为某些类定义一种“制作新版本” - 例如,如果您有一个类 x(a :int, b:String, c:double).. . 它会有这样的功能:
class x( a: Integer, b : String, c : Double) extends CanMakeNew
{
def newValue() = x( a, b, c)
}
Run Code Online (Sandbox Code Playgroud)
我无法控制它 - 但不想每次都实现它。或者,嗯……永远。在 Scala 中有一种方法可以通过反射来迭代构造函数参数值吗?我可以使用反射来查看参数类型- 但由于该模块的参数名称尚未打开,我无法打开它 - 我无法将这些与类中存储的值相关联。从根本上说,我正在寻找实现以下特征的方法:
trait CanMakeNewDoneForMe extends CanMakeNew {
def newValue() {I need the code that goes here}
Run Code Online (Sandbox Code Playgroud)
那么scala反射有没有办法检查构造函数或检查对象并看到“啊,这是构造函数中的第三个参数”?
我需要通过反射调用本地通用方法,但我不知道该怎么做。
我的核心问题是我使用反射从一组从 MySQL 数据库读取 EAV 数据的查询中填充 POCO 对象。我很高兴展示这段代码,但它又长又复杂。我创建了一个简化的示例,我认为它很好地总结了问题。
考虑这个代码:
void Main()
{
var repository = new Repository();
repository.Store<Foo>(xs => xs.Count());
int Compute<M>(string[] source) => repository.Fetch<M>().Invoke(source);
Console.WriteLine(Compute<Foo>(new[] { "A", "B" }));
}
public class Foo { }
public class Repository
{
private Dictionary<Type, object> _store = new Dictionary<Type, object>();
public void Store<T>(Func<string[], int> value)
{
_store[typeof(T)] = value;
}
public Func<string[], int> Fetch<T>()
{
return (Func<string[], int>)_store[typeof(T)];
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个Repository可以存储Func<string[], int>索引的类型Type。
在我的Main方法中,我实例化了一个实例Repository …
几天前我开始学习 golang,发现reflect.Valueof()和Value.Elem()很混乱。这两个函数/方法有什么区别以及如何正确使用它们?
两个函数/方法都返回一个值,并根据 go doc
ValueOf 返回一个初始化为接口 i 中存储的具体值的新值。ValueOf(nil) 返回零值。
Elem 返回接口 v 包含的值或指针 v 指向的值。如果 v 的 Kind 不是 Interface 或 Ptr,它会发生恐慌。如果 v 为零,则返回零值。
我从 stackoverflow 上的一篇文章中找到了这段代码,但仍然不明白何时使用 .Elem()
func SetField(obj interface{}, name string, value interface{}) error {
// won't work if I remove .Elem()
structValue := reflect.ValueOf(obj).Elem()
structFieldValue := structValue.FieldByName(name)
if !structFieldValue.IsValid() {
return fmt.Errorf("No such field: %s in obj", name)
}
if !structFieldValue.CanSet() {
return fmt.Errorf("Cannot set %s field value", name)
}
structFieldType := …Run Code Online (Sandbox Code Playgroud) 根据 Pashov 的博客文章,我有以下静态方法用于在过滤器选项之间进行选择。
public static class ExpressionRetriever
{
private static MethodInfo containsMethod = typeof(string).GetMethod("Contains");
private static MethodInfo startsWithMethod = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
private static MethodInfo endsWithMethod = typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) });
public static Expression GetExpression<T>(ParameterExpression param, ExpressionFilter filter)
{
MemberExpression member = Expression.Property(param, filter.PropertyName);
ConstantExpression constant = Expression.Constant(filter.Value);
switch (filter.Comparison)
{
case Comparison.Equal:
return Expression.Equal(member, constant);
case Comparison.GreaterThan:
return Expression.GreaterThan(member, constant);
case Comparison.GreaterThanOrEqual:
return Expression.GreaterThanOrEqual(member, constant);
case Comparison.LessThan:
return Expression.LessThan(member, constant);
case Comparison.LessThanOrEqual:
return Expression.LessThanOrEqual(member, …Run Code Online (Sandbox Code Playgroud) 我知道,有人问过类似的问题,但我没有找到这种情况的答案:
type ExportedStruct struct{ //comes from a dependency, so I can't change it
unexportedResource ExportedType
}
Run Code Online (Sandbox Code Playgroud)
我想打电话给一个出口的方法Close()上unexportedResource。
我所做的是:
rs := reflect.ValueOf(myExportedStructPtr).Elem() //myExportedStructPtr is a pointer to an ExportedStruct object
resourceField := rs.FieldByName("unexportedResource")
closeMethod := resourceField.MethodByName("Close")
closeMethod.Call([]reflect.Value{reflect.ValueOf(context.Background())})
Run Code Online (Sandbox Code Playgroud)
,这导致reflect.flag.mustBeExported using value obtained using unexported field。
这很烦人,因为我想运行多个利用 的测试ExportedStruct,但只要不使用底层资源,我就不能。
因为我可以访问私有字段(如解释在这里)我有一点希望,我被允许访问该场莫名其妙的公共方法,太。也许我只是反映错误?
在 Scala 中,我们如何确定一个类是父类的子类还是特征?例如:
trait MyTrait
class MyParentClass()
class MyOtherParentClass()
case class MySubClass() extends MyParentClass with MyTrait
case class MyOtherSubClass() extends MyOtherParentClass
Run Code Online (Sandbox Code Playgroud)
是否可以通过反射 API来确定类是否MySubClass从实例化对象扩展MyParentClass或MyTrait不实例化?给定一个未知的泛型类型T,如果T扩展特定的父类或特征,我有兴趣让它匹配一个案例:
def example[T](): Unit = {
T match {
case if T extends MyParentClass => ...
case if T extends MyOtherParentClass => ...
case if T extends MyOtherTrait => ...
case _ => default case ...
}
Run Code Online (Sandbox Code Playgroud) 是否可以根据类是唯一的公共函数来调用类的函数?我的意思是:
就像是:
double res = MyClass().myFunction(n);
Run Code Online (Sandbox Code Playgroud)
变成
double res = MyClass()[0](n);
Run Code Online (Sandbox Code Playgroud)
double res = MyClass().reflection("myFunction")(n);
Run Code Online (Sandbox Code Playgroud)
但似乎不可能不浪费至少两倍的墨水来写函数名(函数指针和映射中的相应字符串)。