标签: reflection

scala:以可继承的方式检索用于构造类实例的参数?

在scala中,我有一种情况,其中基类/特征被很多子类扩展.我将通过获取类的名称和用于实例化类的参数来序列化子类的实例(以便稍后重构它).使用反射很容易得到类实例的名称,但我不知道如何以不需要我在每个子类中编写代码的方式获取实例的参数.这也需要适用于名称调用的参数.它似乎很棘手,因为每个子类可能有一个完全不同的数量和类型的构造函数参数:

abstract class Base {
  // ideally implements some way of finding out the arguments used to construct this object
  def getArgs = {...}
}

class ChildA() // args would be a 0-tuple

class ChildB(arg1: Int) // getArgs would be a 1-tuple of arg1

class ChildC(arg1: Double, arg2: Boolean) // args would be a 2-tuple of (arg1, arg2)

// etc... 
Run Code Online (Sandbox Code Playgroud)

我想避免的是让每个类实现一个像"getArgs"这样的方法,只返回一个元组,复制构造函数中的参数.任何方式这样做?

我意识到另一种方法是使用某种拦截器来创建对象,但我无法弄清楚如何在不必为每个子类编写样板代码的情况下这样做.

编辑:案例类方法很优雅,但在我的情况下是不合适的,因为我们必须能够允许具体的子类扩展其他具体的子类.

reflection scala

10
推荐指数
1
解决办法
359
查看次数

从接口方法和类方法中获取属性

什么是在方法重载时从类方法和接口方法获取属性值的最佳方法?

例如,我想知道在下面的示例中,带有一个参数的Get方法具有两个属性,值为5和"any",而另一个方法具有值为7和"private"的属性.

public class ScopeAttribute : System.Attribute
{
    public string Allowed { get; set; }    
}

public class SizeAttribute : System.Attribute
{
    public int Max { get; set; }
}

public interface Interface1
{
    [SizeAttribute( Max = 5 )]
    string Get( string name );

    [SizeAttribute( Max = 7 )]
    string Get( string name, string area );

}

public class Class1 : Interface1
{
    [ScopeAttribute( Allowed = "any" )]
    public string Get( string name )
    {
        return string.Empty;
    }

    [ScopeAttribute( Allowed …
Run Code Online (Sandbox Code Playgroud)

c# reflection custom-attributes

10
推荐指数
2
解决办法
6770
查看次数

Java:InvocationTargetException

我在Java中动态创建类并尝试在其中调用方法,但是,有时候我会得到一个java.lang.reflect.InvocationTargetException.

PageGenerator1.java(动态创建)

import java.io.PrintStream;
import java.util.Map;
public class PageGenerator1 implements DynamicPageGenerator {
    public PageGenerator1() {
    }

    @Override
    public void generate(PrintStream out, Map<String,String> params, Session session) {
        out.print("<html>\r\n<body>\r\n");
        if (session.get("counter") == null) {
                session.set("counter", 2);
                out.println("<h1>Hi "+params.get("name")+" this is your first visit</h1>");
        } else {
                out.println("<h1>This is your "+session.get("counter")+" visit</h1>");
                session.set("counter", 1+((Integer)session.get("counter")));
        }
        out.print("\r\n</body>\r\n</html>");
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图像这样调用它:

    logger.info(
        "Attempting to invoke the method " + generateMethod + " with an instance of " + generatedClassName + "with the following …
Run Code Online (Sandbox Code Playgroud)

java reflection

10
推荐指数
1
解决办法
7万
查看次数

具有泛型的属性的对象类型(例如"Collection`1")中"撇号+数字"的含义是什么?

我有一个MyObject带有property(MyProperty)的object ().我想要得到它的类型名称(即String或MyClass等).我用:

PropertyInfo propInfo = typeof(MyObject).GetProperty("MyProperty");
Console.WriteLine(propInfo.PropertyType.Name);
Console.WriteLine(propInfo.PropertyType.FullName);
Run Code Online (Sandbox Code Playgroud)

简单类型没有问题,但是当MyProperty它是泛型类型时,我在获取它的名字方面遇到了问题(例如Collection<String>).它打印:

Collection`1

System.Collections.ObjectModel.Collection`1 [[System.String,mscorlib,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]

那是什么`1?我怎样才能获得" Collection<String>"?

.net c# generics reflection fully-qualified-naming

10
推荐指数
2
解决办法
2048
查看次数

如何从Objective-C中的类属性中获取值?

我想使用反射从objective-c类中获取变量值.

company.h看起来像

@interface Company : NSObject {
}
@property (nonatomic, retain) NSString* phone;
- (NSString*) getPropertyValueByName: (NSString*) paramName;
Run Code Online (Sandbox Code Playgroud)

company.m看起来像

@implementation Company
@synthesize phone;
- (NSString*) getPropertyValueByName: (NSString*) paramName
{    
    id me = self;
    value = [me objectForKey: paramName];
    return value;
}
@end
Run Code Online (Sandbox Code Playgroud)

我这样使用:

Company* comp = [Company new];
comp.phone = @"+30123456";

NSString* phone = comp.getPropertyValueByName(@"phone");
Run Code Online (Sandbox Code Playgroud)

我得到的是一个例外:

-[Company objectForKey:]: unrecognized selector sent to instance
Run Code Online (Sandbox Code Playgroud)

iphone reflection cocoa-touch objective-c

10
推荐指数
2
解决办法
6294
查看次数

如何检查当前方法的参数是否有注释并在Java中检索该参数值?

考虑以下代码:

public example(String s, int i, @Foo Bar bar) {
  /* ... */
}
Run Code Online (Sandbox Code Playgroud)

我想检查方法是否有注释@Foo并获取参数或如果没有@Foo找到注释则抛出异常.

我目前的方法是首先获取当前方法,然后遍历参数注释:

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

class Util {

    private Method getCurrentMethod() {
        try {
            final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
            final StackTraceElement ste = stes[stes.length - 1];
            final String methodName = ste.getMethodName();
            final String className = ste.getClassName();   
            final Class<?> currentClass = Class.forName(className);
            return currentClass.getDeclaredMethod(methodName);
        } catch (Exception cause) {
            throw new UnsupportedOperationException(cause);
        }  
    }

    private Object getArgumentFromMethodWithAnnotation(Method method, Class<?> annotation) {
        final …
Run Code Online (Sandbox Code Playgroud)

java reflection methods annotations class

10
推荐指数
1
解决办法
9393
查看次数

如何通过Java中的反射获取方法参数的值?

考虑以下代码:

public void example(String s, int i, @Foo Bar bar) {
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

我对注释的参数的价值感兴趣@Foo.假设我已经通过反射(with Method#getParameterAnnotations())找出了哪个方法参数具有@Foo注释.(我知道它是参数列表的第三个参数.)

我现在如何检索bar进一步使用的值?

java reflection parameters arguments annotations

10
推荐指数
1
解决办法
1万
查看次数

如何通过反射确定某个字段是否有"新"修饰符?

可能重复:
如何使用反射检测字段上的"新"修改器?

有以下声明

public class B : A
{
    public new string Name;
}
Run Code Online (Sandbox Code Playgroud)

如何确定该字段的FieldInfo实例是否具有"新"修饰符?

c# reflection

10
推荐指数
2
解决办法
460
查看次数

WP7.1上的匿名类型和Get访问器?

我正在尝试将一个简单的对象写入Dictionary转换器,如下所示:

public static class SimplePropertyDictionaryExtensionMethods
{
    public static IDictionary<string,string> ToSimplePropertyDictionary(this object input)
    {
        if (input == null)
            return new Dictionary<string, string>();

        var propertyInfos = from property in input.GetType()
                                .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.GetProperty)
                            where property.CanRead
                            select property;

        return propertyInfos.ToDictionary(x => x.Name, x => input.GetPropertyValueAsString(x));
    }

    public static string GetPropertyValueAsString(this object input, PropertyInfo propertyInfo)
    {
        var value = propertyInfo.GetGetMethod().Invoke(input, new object[] {});
        if (value == null)
            return string.Empty ;

        return value.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将其称为:

var test = (new { …
Run Code Online (Sandbox Code Playgroud)

c# reflection windows-phone-7 methodaccessexception

10
推荐指数
1
解决办法
1237
查看次数

通过相同对象实例(或基础)的反射调用私有/受保护的方法

是否可以通过反射调用受保护的方法.我用这个:

 Me.GetType.InvokeMember(Stages(CurrentStage), 
                         Reflection.BindingFlags.InvokeMethod, 
                         Nothing, 
                         Me, 
                         Nothing)
Run Code Online (Sandbox Code Playgroud)

总是调用没有参数或返回的方法.我的想法是我的对象的用户(业务逻辑的事务处理)继承基类添加一个私有方法来加载.然后,他们按照他们希望触发的顺序将这些方法名称添加到列表中,上面的代码将负责触发它们.

它适用于公共方法,但不适用于同一类中的私有或受保护方法(受保护,因为我有一些'标准'预构建方法要添加到基类).实际上,我可以将这些方法公之于众,但我内心的书呆子不会允许我这样做......

我假设这是一个安全功能.有没有办法解决这个问题,或者有没有人对如何进行有任何建议,但保持我美味,美味的能见度调节剂?

(注意:ITS在VB.NET中,但如果你觉得这是一个C#答案就好了).

c# vb.net reflection

10
推荐指数
2
解决办法
1万
查看次数