标签: reflection

在Java中按名称设置变量

我希望用Java来实现一些东西:

class Foo{
 private int lorem; //
 private int ipsum;      

 public setAttribute(String attr, int val){
  //sets attribute based on name
 }

 public static void main(String [] args){
  Foo f = new Foo();
  f.setAttribute("lorem",1);
  f.setAttribute("ipsum",2);
 }

 public Foo(){}
}
Run Code Online (Sandbox Code Playgroud)

...基于变量名设置变量而不使用硬编码的变量名并且不使用任何其他数据结构.这可能吗?

java reflection eval

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

C#反射:在成员字段上查找属性

我可能会错误地问这个问题,但可以/如何在自己的课程中找到字段......例如......

public class HtmlPart {
  public void Render() {
    //this.GetType().GetCustomAttributes(typeof(OptionalAttribute), false);
  }
}

public class HtmlForm {
  private HtmlPart _FirstPart = new HtmlPart();      
  [Optional] //<-- how do I find that?
  private HtmlPart _SecondPart = new HtmlPart();
}
Run Code Online (Sandbox Code Playgroud)

或者我可能只是错误地执行此操作...如何调用方法然后检查应用于自身的属性?

此外,为了这个问题 - 我很好奇是否有可能在不知道/访问父类的情况下找到属性信息!

c# reflection attributes field

16
推荐指数
3
解决办法
2万
查看次数

如何判断Type是否实现IList <>?

我想编写一个方法,使用Reflection来判断给定的Type是否实现IList<T>.例如:

IsGenericList(typeof(int))                       // should return false
IsGenericList(typeof(ArrayList))                 // should return false
IsGenericList(typeof(IList<int>))                // should return true
IsGenericList(typeof(List<int>))                 // should return true
IsGenericList(typeof(ObservableCollection<int>)) // should return true
Run Code Online (Sandbox Code Playgroud)

在我的用法中,我可以假设类型将始终是实例化的泛型类型(或者根本不是通用的类型).

不幸的是,这并不像它应该的那么容易.明显的解决方案:

public bool IsGenericList(Type type)
{
    return typeof(IList<>).IsAssignableFrom(type);
}
Run Code Online (Sandbox Code Playgroud)

不起作用; 它总是返回false.显然,非实例化的泛型类型IList<>不会像我期望的那样实现IsAssignable:IList<>不能从中分配List<T>.

我也试过这个:

public bool IsGenericList(Type type)
{
    if (!type.IsGenericType)
        return false;
    var genericTypeDefinition = type.GetGenericTypeDefinition();
    return typeof(List<>).IsAssignableFrom(genericTypeDefinition);
}
Run Code Online (Sandbox Code Playgroud)

即,type转换为非实例化的泛型,如IList<int>- > IList<>,然后再次尝试IsAssignableFrom.当类型是一个实例化将返回true IList<T>,如IList<int>,IList<object>等,但它返回实现类错误IList<T>,如List<int> …

.net generics reflection

16
推荐指数
2
解决办法
9744
查看次数

如何判断javascript对象是Image还是Canvas?

我有一个具有属性的类,可以是Image(即IMG元素)或Canvas.当我将它序列化为JSON时,我需要将其转换为文本字符串.如果它是Canvas,那么我可以调用Canvas#toDataURL.但如果它是一个Image,我首先需要使用Canvas#drawImage将其绘制到Canvas,然后使用toDataURL序列化该画布.

那么如何确定对象是Canvas还是Image?(因为Canvas#drawImage能够接受Image或Canvas对象作为参数,所以必须有办法.)

我已经看到一些程序员测试某些属性或函数是否存在以确定类,但我想知道如果这些对象提供的API发生变化,是否有更智能的方法不会中断.

javascript reflection canvas

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

与Ruby相反的是什么?

如果我有一个类实例,包含几个包含的模块,我可以动态取消包含一个特定的模块(为了替换它)?

谢谢.

ruby reflection

16
推荐指数
3
解决办法
3780
查看次数

应该是两种不相等的类型

我正在尝试调试一些使用反射来加载插件的代码

这是调试代码:

Type a = methodInfo.GetParameters()[0]
    .ParameterType.BaseType;
Type b = typeof(MessageContext);
Debug.WriteLine(a.AssemblyQualifiedName);
Debug.WriteLine(b.AssemblyQualifiedName);
Debug.WriteLine(a.Equals(b));
Run Code Online (Sandbox Code Playgroud)

这是它的输出:

OrtzIRC.Common.MessageContext,OrtzIRC.Common,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null
OrtzIRC.Common.MessageContext,OrtzIRC.Common,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null
False

我不明白是什么让这两种类型不同?

.net c# reflection

16
推荐指数
1
解决办法
2407
查看次数

null类型的参数应该显式地转换为Class <?> []以调用varargs方法

请看下面的示例,第getMethod()一个在Eclipse中生成警告的调用.第二个不起作用,失败了NoSuchMethodException.

对于从类型调用varargs方法,null应明确地转换类型Class<?>[]的参数.也可以将它转换为Class以进行varargs调用.getMethod(String, Class<?>...)Class<Example>

我跟着警告,没有任何工作了.

import java.lang.reflect.Method;


public class Example
{
  public void exampleMethod() { }

  public static void main(String[] args) throws Throwable
  {
   Method defaultNull = Example.class.getMethod("exampleMethod", null);         
   Method castedNull = Example.class.getMethod("exampleMethod", (Class<?>) null);
 }
}
Run Code Online (Sandbox Code Playgroud)

第二个调用产生此错误:

Exception in thread "main" java.lang.NoSuchMethodException: 
    Example.exampleMethod(null)
        at java.lang.Class.getMethod(Class.java:1605)
        at Example.main(Example.java:12)
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释这种行为吗?什么是避免警告的正确方法?

java reflection variadic-functions compiler-warnings

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

如何在Java中找到重载方法?

写点的时候

doit(43, 44, "hello");
Run Code Online (Sandbox Code Playgroud)

编译器知道要调用哪个重载方法.当我想通过反思做同样的事情时,我需要找出自己,方法是

doit(Integer, double, CharSequence...);
Run Code Online (Sandbox Code Playgroud)

并通过类似的东西获得它

Class[] types = {Integer.class, double.class, CharSequence[].class};
declaringClass.getDeclaredMethod("doit", types);
Run Code Online (Sandbox Code Playgroud)

我想知道是否已经允许我写一些东西了

Method m = getMethod(declaringClass, "doit", 43, 44, "hello");
Run Code Online (Sandbox Code Playgroud)

我想知道是否有人这样做了,因为JLS在这方面有点复杂.


实际上,行为与编译器完全相同是不可能的,因为在第1阶段,编译器只接受匹配而没有装箱和拆箱的方法.当getMethod从上面调用我的假设时,原语和它们的包装器之间的区别已经丢失(因为通过varargs传递参数时的自动装箱).这个问题似乎没有解决方案,所以让我们忽略它.

如答案所示,BeanUtils.invokeMethod接近.它应该找到最佳匹配,无论它意味着什么.查看MethodUtils.getMatchingAccessibleMethod显示了这一点

  • 它对varargs一无所知
  • 这是非确定性的

所以我正在寻找更好的东西.

java reflection overloading

16
推荐指数
1
解决办法
4065
查看次数

kotlin反射得到字段列表

foo.getClass().getFields()Kotlin中的java反射是否相同?当我知道它的名字时,我只能发现我可以访问一个字段,但我想以通用的方式处理字段.

reflection jvm kotlin

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

将接口{}转换为Golang中的map

我正在尝试创建一个可以接受以下的功能

*struct
[]*struct
map[string]*struct
Run Code Online (Sandbox Code Playgroud)

这里struct可以是任何结构,而不仅仅是特定结构.将接口转换为*struct或[]*struct正常工作.但给地图错误.

反映后显示它是map [],但在尝试迭代范围时给出错误.

这是代码

package main

import (
    "fmt"
    "reflect"
)

type Book struct {
    ID     int
    Title  string
    Year   int
}

func process(in interface{}, isSlice bool, isMap bool) {
    v := reflect.ValueOf(in)

    if isSlice {
        for i := 0; i < v.Len(); i++ {
            strct := v.Index(i).Interface()
            //... proccess struct
        }
        return
    }

    if isMap {
        fmt.Printf("Type: %v\n", v)     // map[]
        for _, s := range v {           // Error: cannot …
Run Code Online (Sandbox Code Playgroud)

reflection dictionary interface go

16
推荐指数
3
解决办法
4万
查看次数