我使用反射包来获取任意数组的类型,但得到
prog.go:17: cannot use sample_array1 (type []int) as type []interface {} in function argument [process exited with non-zero status]
Run Code Online (Sandbox Code Playgroud)
如何从数组中获取类型?我知道如何从价值中获取它.
func GetTypeArray(arr []interface{}) reflect.Type {
return reflect.TypeOf(arr[0])
}
Run Code Online (Sandbox Code Playgroud)
我很开心玩Rust很长一段时间都是C#程序员,但我对反思有疑问.
嗯,我认为反思,也许我不需要在这种情况下进行反思,但鉴于Rust是强烈打字我怀疑我做的(我肯定需要它在好的'C#,祝福它的棉袜).
是的,所以说我有这种情况:
use std::collections::HashMap;
fn invoke_an_unknown_function(
hashmap: HashMap<String, String>,
// Something to denote a function I know nothing about goes here
) {
// For each key in the hash map, assign the value
// to the parameter argument whose name is the key
// and then invoke the function
}
Run Code Online (Sandbox Code Playgroud)
我该怎么办?我猜我需要传递一些MethodInfo作为函数的第二个参数,然后用它来解决它的名字是哈希映射中的键的参数并分配值,但我看了一下反射API并发现以下内容:
但他们都没有给我足够的继续开始.那么,我将如何实现上面描述的功能呢?
我有以下POJO:
public interface Shape {
public double calcArea();
public double calcPerimeter();
}
public class Rectangle implement Shape {
// Various properties of a rectangle
}
public class Circle implements Shape {
// Various properties of a circle
}
public class ShapeHolder {
private List<Shape> shapes;
// other stuff
}
Run Code Online (Sandbox Code Playgroud)
我没有问题让GSON序列化ShapeHolder到JSON 的实例.但是当我尝试将该JSON的String反序列化为一个ShapeHolder实例时,我得到错误:
String shapeHolderAsStr = getString();
ShapeHolder holder = gson.fromJson(shapeHodlderAsStr, ShapeHolder.class);
Run Code Online (Sandbox Code Playgroud)
抛出:
Exception in thread "main" java.lang.RuntimeException: Unable to invoke no-args constructor for interface
net.myapp.Shape. Register an …Run Code Online (Sandbox Code Playgroud) 我正在使用Reflection.Emit开发一个在运行时动态创建Assembly的工具.
该工具针对.NET 4.5框架.
我想知道是否可以指定动态生成的程序集所针对的.NET运行时(例如:指定将创建.NET 3.5程序集).
为什么dynamic对象在反射时不能在NameTranslate COM对象上调用这些方法?
使用动态的失败示例:
Type ntt = Type.GetTypeFromProgID("NameTranslate");
dynamic nto = Activator.CreateInstance(ntt);
nto.Init(3,null)
Run Code Online (Sandbox Code Playgroud)
第三行因NotImplementedException而失败,并且消息未实现方法或操作.
使用不同COM对象(WScript.Shell和SendKeys)的类似尝试:
Type shellType = Type.GetTypeFromProgID("WScript.Shell");
dynamic shell = Activator.CreateInstance(shellType);
shell.SendKeys("abc");
Run Code Online (Sandbox Code Playgroud)
回到第一个样本.如果我使用反射并使用InvokeMethod方法调用方法,一切正常.
使用反射的工作示例:
Type ntt = Type.GetTypeFromProgID("NameTranslate");
object nto = Activator.CreateInstance(ntt);
object[] initParams = new object[]{3,null};
ntt.InvokeMember("Init", BindingFlags.InvokeMethod, null, nto, initParams);
Run Code Online (Sandbox Code Playgroud)
我相信这必须与如何创建或标记COM对象有关 - 但是对于我的生活,我在文档,对象浏览器或注册表中看不到任何指示这些COM对象及其子/函数被标记的内容私有或其他通常会抛弃dynamic关键字的东西.
MSDN上的NameTranslate文档:http://msdn.microsoft.com/en-us/library/windows/desktop/aa706046.aspx
test.c的:
#include <stdio.h>
#include <stdlib.h>
struct s {
char a;
int b;
float c;
double d;
};
struct s *create_struct()
{
struct s *res = malloc(sizeof(struct s));
res->a = 1; res->b = 2; res->c = 3.0f; res->d = 4.0;
return res;
}
Run Code Online (Sandbox Code Playgroud)
test.py:
from ctypes import *
class S(Structure):
_fields_ = [
('a', c_byte),
('b', c_int),
('c', c_float),
('d', c_double)
]
lib = CDLL('./test.so')
create_struct = lib.create_struct
create_struct.restype = POINTER(S)
create_struct.argtypes = []
s_ptr = create_struct()
s = s_ptr.contents
print …Run Code Online (Sandbox Code Playgroud) 下面是如何在运行时创建T类型的新实例Manifest:
trait MyTrait
class MyClass1(val name: String) extends MyTrait
class MyClass2(val name: String) extends MyTrait
class Test[T <: MyTrait] {
def createInstance[T](name: String)(implicit m: Manifest[T]): T = {
m.runtimeClass.getConstructors()(0)
.newInstance(name).asInstanceOf[T]
}
def doSomething() {
val myClass = createInstance("joe")
...
}
}
...
val test = new Test[MyClass1]
test.doSomething
Run Code Online (Sandbox Code Playgroud)
createInstance上面的方法创建了一个实现MyTrait和调用具有给定字符串的构造函数的类的新实例.我该如何实现相同的TypeTag?
使用scala.reflect.runtime._重新实现
下面是Test按照som-snytt的建议重新实现的类:
class Test[T <: MyTrait] {
import scala.reflect.runtime._
import scala.reflect.runtime.universe._
def createInstance[T: TypeTag](name: String): T = {
val tt = typeTag[T] …Run Code Online (Sandbox Code Playgroud) 我一直在研究一种实例化方法,它允许我将各种类似的类打包到一个外部类中.然后,我可以通过将该类型的名称传递给构造函数来实例化每个唯一的类类型.经过大量的研究和错误,这就是我想出的.我留下了一个错误,以证明我的问题.
import java.lang.reflect.Constructor;
public class NewTest
{
public static void main(String[] args)
{
try
{
Class toRun = Class.forName("NewTest$" + args[0]);
toRun.getConstructor().newInstance();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
public NewTest(){}
private class one //Does not instantiate
{
public one()
{
System.out.println("Test1");
}
}
private static class two //Instantiates okay
{
public two()
{
System.out.println("Test2");
}
}
}
Run Code Online (Sandbox Code Playgroud)
按照我的意图编译此代码并java NewTest two在输出中运行结果Test2.
运行java NewTest one结果
java.lang.NoSuchMethodException: NewTest$one.<init>()
at java.lang.Class.getConstructor(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at …Run Code Online (Sandbox Code Playgroud) 我有一个简单的类型与自定义类型转换器,在运行时编译和加载.但是TypeDescriptor.GetConverter()找不到合适的转换器.这是一个独立的例子
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
public class Program
{
private static string src =
@"
using System;
using System.ComponentModel;
namespace LoadMe
{
[TypeConverter(typeof(FooConverter))]
public class Foo
{
}
public class FooConverter : TypeConverter
{
// stuff
}
}
";
public static void Main()
{
var codeProvider = new CSharpCodeProvider(new Dictionary<string, string>{{ "CompilerVersion", "v4.0" }});
var compileParameters = new CompilerParameters(new[] { "System.dll" }) { GenerateInMemory = true };
var compilerResults = codeProvider.CompileAssemblyFromSource(compileParameters, src);
if (compilerResults.Errors.Count …Run Code Online (Sandbox Code Playgroud) [AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
...
}
Run Code Online (Sandbox Code Playgroud)
我想在同时使用这个自定义属性的属性和的Fileds而不是其他.如何分配多个目标(AttributeTargets.Property和AttributeTargets.Field)?或者这是不可能的?
而AttributeTargets.All这不是我想要的.
reflection ×10
c# ×4
.net ×2
dynamic ×2
java ×2
arrays ×1
attributes ×1
com ×1
ctypes ×1
go ×1
go-reflect ×1
gson ×1
python ×1
rust ×1
scala ×1
slice ×1
type-safety ×1