使用实验性的Scala 2.10反射,当我尝试在一个惰性val的字段上调用FieldMirror.get()时,它返回null.有没有办法用反射评估懒惰的val?之后get()函数不应再返回null.
考虑这个例子:
case class Person(val firstName: String,
val lastName: String) {
lazy val name = firstName + " " + lastName
}
import scala.reflect.runtime.{universe => ru}
val runtimeMirror = ru.runtimeMirror(getClass.getClassLoader)
val fred = Person("Fred", "Smith")
val instanceMirror = runtimeMirror.reflect(fred)
val nameTerm = ru.typeOf[Person].declaration(ru.newTermName("name")).asTerm
val nameLazy = instanceMirror.reflectField(nameTerm)
nameLazy.get
>>> res8: Any = null
fred.name
>>> res9: String = Fred Smith
nameLazy.get
>>> res10: Any = Fred Smith
Run Code Online (Sandbox Code Playgroud) 最近我遇到了Reflection API,令我惊讶的是我们可以访问甚至更改私有变量.我尝试了以下代码
import java.lang.reflect.Field;
public class SomeClass{
private String name = "John";
}
public class Test{
public static void main(String args[]) throws Exception {
SomeClass myClass = new SomeClass();
Field fs = myClass.getClass().getDeclaredField("name");
fs.setAccessible(true);
System.out.println("Variable is " + fs.getName() + " and value is "
+ fs.get(myClass));
fs.set(myClass, "Sam");
System.out.println("Variable is " + fs.getName() + " and value is "
+ fs.get(myClass));
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了以下输出.
Variable is name and value is John
Variable is name and value is Sam
Run Code Online (Sandbox Code Playgroud)
我们说Java是一种面向对象的语言,它的主要特性是数据封装,继承,多态......等不是反射API改变了数据封装的目的吗?为什么我们必须使用Reflection …
我试图在Scala反射中看到一个注释,到目前为止还没有骰子.我错过了什么?
我的注释:( Java)
@Target({ElementType.PARAMETER}) // Also tried ElementType.CONSTRUCTOR
@Retention(RetentionPolicy.RUNTIME)
public @interface MongoKey {
String info = "";
}
Run Code Online (Sandbox Code Playgroud)
尝试使用Scala反射访问它的部分:
case class One(
@MongoKey name : String,
stuff : List[String]
)
val targetObj = One("FOO", List("a","b"))
val targetType = typeOf[One]
// Given an object (case class) the Type of the case class, and a field name,
// retrieve the typed field object from the case class.
def unpack[T](target: T, t: Type, name: String): (Any, Type) = {
val im = cm.reflect(target)(ClassTag(target.getClass)) …Run Code Online (Sandbox Code Playgroud) 我甚至不确定这是否可能,如果不是,那么道歉.我搜索广泛,没有找到我要找的东西.
基本上我们有一个由第三方制作的应用程序,完全生硬的是垃圾.我们有一个特定的问题,并设法使用ILSpy跟踪DLL中的方法的问题.显然,我们没有(也无法获得)源代码,并且有问题的公司不愿意在任何合理的时间范围内解决问题.
所以,我们已经调查了各种调查途径并且没有提出任何建议.我一直在研究是否可以使用反射完成这一点,这几乎是我们让这个工作的最后希望.简而言之,我想做的是以下内容:
我在调查过程中发现了TypeBuilder.DefineMethodOverride以及StackOverflow中的一个页面,它看起来很相似,但并不是我想要的.
http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.definemethodoverride.aspx
任何建议赞赏!
安德鲁
我有另一个可能的想法是生成一个包含覆盖函数的分部类,但这似乎也不可行.
如何创建appdomain,向其添加程序集,然后销毁该app域?这是我尝试过的:
static void Main(string[] args)
{
string pathToExe = @"A:\Users\Tono\Desktop\ConsoleApplication1.exe";
AppDomain myDomain = AppDomain.CreateDomain("MyDomain");
Assembly a = Assembly.Load(System.IO.File.ReadAllBytes(pathToExe));
myDomain.Load(a.FullName); // Crashes here!
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
myDomain.Load(File.ReadAllBytes(pathToExe));
Run Code Online (Sandbox Code Playgroud)
如何将程序集添加到appdomain.一旦我这样做,我可以通过反射找到方法执行它,然后销毁appdomain
我得到的例外是:
无法加载文件或程序集"ConsoleApplication1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null"或其依赖项之一.该系统找不到指定的文件.
我有一个带有泛型返回类型的方法的接口,并且在运行时有一些间接实现该接口的类的实例.现在我想找出使用反射的每个实现的实际返回类型.
(我的想法是使用这种机制来定义使用接口的策略,并在运行时从一组策略实现中找到匹配的策略(特定的返回类型),而不必引入暴露类型的冗余辅助方法).
更具体地说,让我们考虑以下场景:
private interface DAO <I extends Serializable, E> {
public E getById (I id);
}
private abstract class AbstractDAO <T> implements DAO<Integer, T> {
@Override
public T getById (Integer id) {
// dummy implementation, just for this example
return null;
}
}
private class PersonDAO extends AbstractDAO<Person> {
}
private class PersonDAOExtension extends PersonDAO {
}
Run Code Online (Sandbox Code Playgroud)
在运行时,我想找出给定的class(PersonDAOExtension.class)将为该方法返回哪种类型getById(..)(期望为:) Person.class.
使用反射,我可以找出Type从这个方法返回的泛型.在这种情况下,它是一个TypeVariable(但也可以是 …
尝试创建两个发出的委托字典,以便在动态获取/设置属性值时提高性能.
码:
Properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && !p.GetIndexParameters().Any())
.AsEnumerable();
PropertyGetters = Properties.ToDictionary(p => p.Name, p => (Func<object, object>)Delegate.CreateDelegate(typeof(Func<object, object>), p.GetGetMethod()));
PropertySetters = Properties.Where(p => p.GetSetMethod() != null)
.ToDictionary(p => p.Name, p => (Action<object, object>)Delegate.CreateDelegate(typeof(Action<object, object>), p.GetSetMethod()));
Run Code Online (Sandbox Code Playgroud)
但是我得到以下异常:
无法绑定到目标方法,因为其签名或安全透明性与委托类型的签名或安全透明性不兼容.
从我所看到的,这将由静态/索引/值类型属性引起,该Properties集合不包含静态或索引属性,但我确实需要它来处理值类型属性,如int和double.
如何在保持代码抽象和避免泛型的同时创建我需要的getter/setter?
我有一个方法,通过7,753+对象使用循环并获取每个对象的每个属性的值.每个对象都有14属性.
private void InitializeData(IList objects, PropertyInfo[] props, List<DPV> dataPs, List<Dictionary<string, object>> tod)
{
foreach (var item in objects)
{
var kvp = new Dictionary<string, object>();
foreach (var p in props)
{
var dataPs = dataPs.FirstOrDefault(x => x.Name == p.Name);
object returnData;
if (dataPoint != null)
{
int maxLength = (dataP.MaxLength == null) ? 0 : (int) dataP.MaxLength;
returnData = p.GetValue(item, null);
if (!string.IsNullOrEmpty(dataP.FormatString) && !string.IsNullOrEmpty(returnData.ToString()))
{
returnData = FormatDataForDisplay(returnData, dataP, maxLength, "", 8);
}
}
else …Run Code Online (Sandbox Code Playgroud) 在以下类型中:
MyClass = class(TInterfacedPersistent)
private
FMyProperty: Integer;
published
procedure setMyProperty(Value: Integer); virtual;
property MyProperty: Integer read FMyProperty write setMyProperty;
Run Code Online (Sandbox Code Playgroud)
我想通过RTTI知道"MyProperty"属性的setter方法的名称.我尝试过以下方法:
procedure ShowSetterMethodsNames(pMyObject: TObject);
var
vPropList: TPropList;
vCount, I: Integer;
begin
vCount:= GetPropList(pMyObject.ClassInfo, tkProperties, @vPropList);
for I:= 0 to vCount -1 do
begin
if Assigned(vPropList[I]^.SetProc) then
ShowMessage(pMyObject.ClassType.MethodName(vPropList[I]^.SetProc));
end;
end;
Run Code Online (Sandbox Code Playgroud)
虽然指针不是nil,但我所有的都是空消息.有人给我一些小费吗?
PS:我正在使用Delphi XE4,我知道我应该使用扩展RTTI而不是经典,但无论如何,我不能在两个功能中做我想要的...所以,任何帮助将不胜感激.谢谢你的回复.
最终版,问题解决了:
这是代码工作,基于(我的朋友和...的帮助)RTTI单元(TRTTIInstanceProperty类的DoSetValue方法):
procedure ShowVirtualSettersNames(pObject: Pointer);
var
vSetter, vPointer: Pointer;
vPropList: TArray<TRttiProperty>;
vProp: TRttiProperty;
begin
vPropList:= RTTIUtils.ExtractProperties(TObject(pObject).ClassType); // Helper to get properties from a type, based in extended RTTI
for …Run Code Online (Sandbox Code Playgroud) 我目前正在研究java安全性并遇到了一个奇怪的现象.java中的SecurityManager存储在java.lang.System中的"security"字段中.有趣的是,该领域似乎受到反射访问的保护,这确实有意义,但据我所知,这个领域是唯一的.所以这是一个例子:
for(Field f : System.class.getDeclaredFields())
System.out.println(f);
Run Code Online (Sandbox Code Playgroud)
输出
public static final java.io.InputStream java.lang.System.in
public static final java.io.PrintStream java.lang.System.out
public static final java.io.PrintStream java.lang.System.err
private static volatile java.io.Console java.lang.System.cons
private static java.util.Properties java.lang.System.props
private static java.lang.String java.lang.System.lineSeparator
Run Code Online (Sandbox Code Playgroud)
有趣的是:该领域被宣布为
private static volatile SecurityManager security = null;
Run Code Online (Sandbox Code Playgroud)
不在列表中,肯定是打电话给
System.class.getDeclaredField("security");
Run Code Online (Sandbox Code Playgroud)
产生NoSuchFieldException.因为我在网上找不到任何关于这个的信息,我很确定这个字段曾经可以通过反思访问(例如,参见2010年的博客文章,描述访问该字段)我想知道a)是否已实现作为快速修复,以防止通过反射轻松禁用安全管理器和b)如何实现(或者更确切地说,有任何机会保护其他私有字段免受反射).
reflection ×10
c# ×4
java ×3
scala ×2
.net ×1
annotations ×1
appdomain ×1
asp.net-3.5 ×1
assemblies ×1
delphi ×1
delphi-xe4 ×1
dll ×1
generics ×1
private ×1
rtti ×1
security ×1