什么是反射?我阅读了关于这个主题的维基百科文章,我理解它是一种元编程,程序可以在运行时自行修改,但这意味着什么?在什么样的情况下这是一个好的方法,何时最好使用它?
我有一些辅助方法可以将枚举值转换为适合HTML <select>元素显示的字符串列表.我想知道是否可以将这些重构为单一的多态方法.
这是我现有方法之一的示例:
/**
* Gets the list of available colours.
*
* @return the list of available colours
*/
public static List<String> getColours() {
List<String> colours = new ArrayList<String>();
for (Colour colour : Colour.values()) {
colours.add(colour.getDisplayValue());
}
return colours;
}
Run Code Online (Sandbox Code Playgroud)
我仍然是Java泛型的新手,所以我不确定如何将泛型枚举传递给该方法并在for循环中使用它.
请注意,我知道有问题的枚举都将具有该getDisplayValue方法,但遗憾的是它们不共享定义它的常见类型(我不能引入一个),所以我想这将是必须反复访问的.. .?
在此先感谢您的帮助.
是否有投一个更快的方法Fun<TEntity, TId>来Func<TEntity, object>
public static class StaticAccessors<TEntity>
{
public static Func<TEntity, TId> TypedGetPropertyFn<TId>(PropertyInfo pi)
{
var mi = pi.GetGetMethod();
return (Func<TEntity, TId>)Delegate.CreateDelegate(typeof(Func<TEntity, TId>), mi);
}
public static Func<TEntity, object> ValueUnTypedGetPropertyTypeFn(PropertyInfo pi)
{
var mi = typeof(StaticAccessors<TEntity>).GetMethod("TypedGetPropertyFn");
var genericMi = mi.MakeGenericMethod(pi.PropertyType);
var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
//slow: lambda includes a reflection call
return x => typedGetPropertyFn.Method.Invoke(x, new object[] { }); //can we replace this?
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在返回的lambda中转换typedGetPropertyFn为Func<TEntity, object>没有反射代码,如上例所示?
编辑:添加修改后的解决方案
好的,感谢280Z28引导我沿着正确的道路前进,我已经将其包含在下面的最终解决方案中.我已将反射代码留在那里,用于不支持表达式的平台.对于这样做的平台来说,它可以获得26x …
鉴于:
class A
{
public void m(List l) { ... }
}
Run Code Online (Sandbox Code Playgroud)
假设我想m用反射调用方法,将ArrayList作为参数传递给m:
List myList = new ArrayList();
A a = new A();
Method method = A.class.getMethod("m", new Class[] { myList.getClass() });
method.invoke(a, Object[] { myList });
Run Code Online (Sandbox Code Playgroud)
第getMethod3行将抛出,NoSuchMethodException因为myList的运行时类型是ArrayList,而不是List.
有没有一个很好的通用方法,不需要知道A类的参数类型?
我使用反射来看看是否被连接到一个类的属性的注释,是一种特定类型的.目前我在做:
if("javax.validation.Valid".equals(annotation.annotationType().getName())) {
...
}
Run Code Online (Sandbox Code Playgroud)
这让我觉得有点笨拙,因为它依赖于一个完全限定的类名字符串.如果命名空间将来发生更改,则可能会导致细微错误.
我想要做:
if(Class.forName(annotation.annotationType().getName()).isInstance(
new javax.validation.Valid()
)) {
...
}
Run Code Online (Sandbox Code Playgroud)
但它javax.validation.Valid是一个抽象类,无法实例化.有没有办法模拟instanceof(或基本上使用isInstance)对接口或抽象类?
我使用.class-operator向泛型类提供有关包含类型的信息.对于非通用包含类型,例如Integer.class,这没有任何问题.但是包含的类型是通用的,例如List<Integer>.class,List.class它会导致关于类转换的编译时错误.
有办法规避错误,但我很好奇这里发生了什么.有人可以解释发生了什么吗?为什么事情就像它们一样?以及解决问题的最佳方法是什么?
以下行演示了此问题:请注意外部泛型类型需要Class<T>作为参数,因此在这种情况下Class<List<Integer>>.
Class<Integer> tInt = Integer.class; // Works as expected.
Class<List> tList = List.class; // Works with warning, but is not
// what i'm looking for.
Class<List<Integer>> tListInt1 = List.class; // Error
Class<List<Integer>> tListInt2 = (Class<List<Integer>>) List.class; // Error
Class<List<?>> tListGeneric = (Class<List<Integer>>) List.class; // Error
Run Code Online (Sandbox Code Playgroud)
下一行有效:
Class<List<Integer>> tListInt3 =
(Class<List<Integer>>) ((Class<Integer>)List.class);
Run Code Online (Sandbox Code Playgroud)
为什么声明tListInt2和tListGeneric给出和错误?为什么upcast然后downcast而tListInt3不会产生错误?有更好的方式申报tListInt3吗?
亲切的问候,
Kasper van den Berg
PS.如果您希望将代码视为需要此类型信息的外部通用容器,请告诉我们.如果需要,我会发布它.
我有一个带有getter和setter的2个POJO类,现在我正在尝试获取该类的所有类实例变量.
我知道我们可以用反射怎么做?
这是我的POJO类,它将扩展我的反射类.
class Details{
private int age;
private String name;
}
Run Code Online (Sandbox Code Playgroud)
反思类是这样的:
class Reflection{
public String toString(){
return all the fields of that class
}
Run Code Online (Sandbox Code Playgroud) 考虑下面的一段代码:
public class A<T> { }
public class B<T> : A<T> { }
Run Code Online (Sandbox Code Playgroud)
在这种情况下:
var a = typeof(A<>).GenericTypeArguments.Length;
Run Code Online (Sandbox Code Playgroud)
a有价值0,这并不奇怪.然而,这对我来说是出乎意料的:
var b = typeof(B<>).BaseType.GenericTypeArguments.Length;
Run Code Online (Sandbox Code Playgroud)
哪里b有价值1.所以它使用一个不存在的名称"T"关闭,只做GetGenericTypeDefinition它就会再次打开它.这是为什么?
我正在使用.net核心和dapper,第一个没有DataTables,第二个使用它们用于TVP.
我试图将a转换List<T>为a List<SqlDataRecord>,使用此列表创建一个SqlParameter然后将其转换为DynamicParameter但遗憾的是我得到了:The member of type Microsoft.SqlServer.Server.SqlDataRecord cannot be used as a parameter value
玩了一下之后IDynamicParameters,我就开始了.
扩展方法 IEnumerable
public static DynamicWrapper toTVP<T>(this IEnumerable<T> enumerable, string tableName, string typeName)
{
List<SqlDataRecord> records = new List<SqlDataRecord>();
var properties = typeof(T).GetProperties().Where(p => Mapper.TypeToSQLMap.ContainsKey(p.PropertyType));
var definitions = properties.Select(p => Mapper.TypeToMetaData(p.Name, p.PropertyType)).ToArray();
foreach (var item in enumerable)
{
var values = properties.Select(p => p.GetValue(item, null)).ToArray();
var schema = new SqlDataRecord(definitions);
schema.SetValues(values);
records.Add(schema);
}
SqlParameter result = new SqlParameter(tableName, SqlDbType.Structured); …Run Code Online (Sandbox Code Playgroud) reflection ×10
java ×5
c# ×4
generics ×2
.net-core ×1
annotations ×1
casting ×1
covariance ×1
dapper ×1
definition ×1
enums ×1
instanceof ×1
isinstance ×1
lambda ×1
polymorphism ×1
sql ×1