我希望用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)
...基于变量名设置变量而不使用硬编码的变量名并且不使用任何其他数据结构.这可能吗?
我可能会错误地问这个问题,但可以/如何在自己的课程中找到字段......例如......
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)
或者我可能只是错误地执行此操作...如何调用方法然后检查应用于自身的属性?
此外,为了这个问题 - 我很好奇是否有可能在不知道/访问父类的情况下找到属性信息!
我想编写一个方法,使用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> …
我有一个具有属性的类,可以是Image(即IMG元素)或Canvas.当我将它序列化为JSON时,我需要将其转换为文本字符串.如果它是Canvas,那么我可以调用Canvas#toDataURL.但如果它是一个Image,我首先需要使用Canvas#drawImage将其绘制到Canvas,然后使用toDataURL序列化该画布.
那么如何确定对象是Canvas还是Image?(因为Canvas#drawImage能够接受Image或Canvas对象作为参数,所以必须有办法.)
我已经看到一些程序员测试某些属性或函数是否存在以确定类,但我想知道如果这些对象提供的API发生变化,是否有更智能的方法不会中断.
我正在尝试调试一些使用反射来加载插件的代码
这是调试代码:
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
我不明白是什么让这两种类型不同?
请看下面的示例,第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)
有人可以向我解释这种行为吗?什么是避免警告的正确方法?
写点的时候
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显示了这一点
所以我正在寻找更好的东西.
foo.getClass().getFields()Kotlin中的java反射是否相同?当我知道它的名字时,我只能发现我可以访问一个字段,但我想以通用的方式处理字段.
我正在尝试创建一个可以接受以下的功能
*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 ×10
java ×3
.net ×2
c# ×2
attributes ×1
canvas ×1
dictionary ×1
eval ×1
field ×1
generics ×1
go ×1
interface ×1
javascript ×1
jvm ×1
kotlin ×1
overloading ×1
ruby ×1