标签: reflection

用变量实例化

我想知道Java实例化的一些事情.让我们举一个例子,我想根据这样的条件实例化一个类:

Animal a = null;
if (string.equals("Dog")) a = new Dog();
else if (string.equals("Cat") a = new Cat();
etc...
Run Code Online (Sandbox Code Playgroud)

我知道它有效,但我想做这样的事情:而不是做a = new Dog();
我想做这样的事情:( a = new string();string== "Dog")

基本上在运行时,字符串被"Dog"替换.我知道可以使用API​​ Reflection(with Class.forName(string)).

但是new运营商有可能吗?

java oop reflection

0
推荐指数
1
解决办法
54
查看次数

Java反映了Class.forName失败

使用:

final Class<?> c = Class.forName(path);
Run Code Online (Sandbox Code Playgroud)

以下是这些类的存在位置:http://prntscr.com/juqp7g

这是错误:

java.lang.ClassNotFoundException: interfaces/container/InventoryComponentAction
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at scripts.action.ActionManager.init(ActionManager.java:48)
at scripts.system.Application.lambda$0(Application.java:17)
at scripts.system.Application.log(Application.java:29)
at scripts.system.Application.main(Application.java:17)
Run Code Online (Sandbox Code Playgroud)

java reflection syntax class classnotfoundexception

0
推荐指数
1
解决办法
99
查看次数

为什么超类字段的泛型类型不会被删除到子类型中的具体绑定?

package ir.openuniverse;

public class Main {
    public static void main(String[] args) throws NoSuchFieldException {
        System.out.println(A.class.getField("t").getType().getName());
    }
}

class A extends B<D> {}
class B<T extends C> {
    public T t;
}

class C {}
class D extends C {}
Run Code Online (Sandbox Code Playgroud)

输出是ir.openuniverse.C.为什么?我期待D!


编辑:

这个问题不是关于变通方法或替代方法.所以答案不是解决方法.对于其他方式,请参阅下面的回答.

java generics reflection type-erasure

0
推荐指数
1
解决办法
102
查看次数

执行不接受参数的方法

给定一个结构的任意实例,我希望能够执行所有不接受参数的公共方法.

例如,在下面的代码中,我希望能够执行X {}.Foo()和X {}.Bar()而不知道它们是否存在.

package main

import (
    "fmt"
    "reflect"
)

type X struct {
    Y string
}

func (x X) Foo() string {
    return x.Y
}

func (x X) Bar() {
}

func (x X) Baz(q string) {
}

func main() {
    fooType := reflect.TypeOf(X{})
    for i := 0; i < fooType.NumMethod(); i++ {
        method := fooType.Method(i)
        fmt.Println(method.Name)
    }
}
Run Code Online (Sandbox Code Playgroud)

reflection go

0
推荐指数
1
解决办法
47
查看次数

如何使用Reflection访问从抽象类继承的字段?

所以我有一个抽象的Geo类来表示3D几何形状,所以它继承了诸如Vector位置和抽象方法之类的字段,比如更新和显示.

由于我的Cube类继承自这个Geo类,我不会重新声明我的字段,我只是在Cube类的构造函数中设置它们.当我没有从Geo继承并在Cube类中声明字段时,我最初没有收到错误.

但是,当我尝试查看Field是否存在时,我注意到它会抛出此错误:

java.lang.NoSuchFieldException: boundBox
Run Code Online (Sandbox Code Playgroud)

这是用于检查字段的Reflection代码(对象是Cube对象):

try {
   Field field = object.getClass().getDeclaredField("boundBox");
} catch(Exception e){
   e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

所以,我不再重新声明"boundBox"字段,因为我已经在Geo抽象类中声明了它.这是我的抽象类和子类的基本部分:

abstract class Geo {
  public Vector pos;
  public BoundingBox boundBox;

  abstract void update();
  abstract void display();
}

class Cube extends Geo {
  public Cube(Vector pos, float dim){
    this.pos = pos; 
    boundBox = new BoundingBox(pos,dim);
  }
  @Override
  void update(){
  }
  @Override
  void display(){
  }
}
Run Code Online (Sandbox Code Playgroud)

java reflection field abstract

0
推荐指数
1
解决办法
284
查看次数

如何使用Select连接属性表达式和lambda?

我想动态创建以下表达式:

e.Collection.Select(inner => inner.Property)
Run Code Online (Sandbox Code Playgroud)

我创建了这个代码来执行它,但是当我执行表达式调用时,我有一个问题,有人知道我做错了什么?

private static Expression InnerSelect<TInnerModel>(IQueryable source, ParameterExpression externalParameter, string complexProperty)
{
    // Creates the expression to the external property. // this generates: "e.Collection".
    var externalPropertyExpression = Expression.Property(externalParameter, complexProperty);

    // Creates the expression to the internal property. // this generates: "inner => inner.Property"
    var innerParameter = Expression.Parameter(typeof(TInnerModel), "inner");
    var innerPropertyExpression = Expression.Property(innerParameter, "Property");
    var innerLambda = Expression.Lambda(innerPropertyExpression, innerParameter);

    return Expression.Call(typeof(Queryable), "Select", new [] { typeof(TInnerModel) }, externalPropertyExpression, innerLambda);
}
Run Code Online (Sandbox Code Playgroud)

错误:

类型'System.Linq.Queryable'上的通用方法'Select'与提供的类型参数和参数兼容.如果方法是非泛型的,则不应提供类型参数.

c# reflection

0
推荐指数
1
解决办法
197
查看次数

如何检查"?" SomeInterface的Class <?>对象实例

简单- -问题,但我开始想我想要实现的东西走错了路.假设我有一个Method正确初始化的对象.

我需要检查该方法是否会返回实现该Comparable接口的对象.

问题是method.getReturnType()返回一个Class<?>对象,我想检查一下这个"?" 实际上是可比较的实例,但我不能写? instanceof Comparable,怎么会这样做呢?

编辑:我知道我可以做result = method.invoke(someObject),然后result instanceof Comparable我需要在我更大的对象的构造函数中进行这些检查,如果我清楚的话,不知道.

java generics reflection instanceof

0
推荐指数
1
解决办法
38
查看次数

如何确定函数返回的值的数量

如何获取函数的返回值长度,效果类似如下:

func Foo() (int, int){
    ...
}
func Bar() (int, float, bool, string, error){
    ...
}
n1 := getReturnLength(Foo) // shall be 2
n2 := getReturnLength(Bar) // shall be 5
Run Code Online (Sandbox Code Playgroud)

我该如何实现getReturnLength功能或平等的功能?

reflection go

0
推荐指数
1
解决办法
101
查看次数

EF Core 2.2中的动态Where子句

我想在我的LINQ查询中动态添加where子句。我具有过滤器属性名称和过滤器属性值,因此我需要构建如下内容:

var assignmentListQuery = context.Assignments;

if (!string.IsNullOrWhiteSpace(bookingStep.FilterPropertyName) && !string.IsNullOrWhiteSpace(bookingStep.FilterPropertyValue))
{
    assignmentListQuery = assignmentListQuery.Where(item => PROPERTYNAME == PROPERTYVALUE)
}

ar assignmentList = await assignmentListQuery.ToListAsync();
Run Code Online (Sandbox Code Playgroud)

我试图获取属性的propertyinfo,在这里我似乎不知道。

var item = context.Set<Assignment>().First();
object value = item.GetType().GetProperty(bookingStep.FilterPropertyName).GetValue(item, null);
Run Code Online (Sandbox Code Playgroud)

有谁知道如何创建这种where子句?

public class Assignment
    {
        /// <summary>
        /// 
        /// </summary>
        [Display(Name = nameof(Id))]
        public int Id { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Display(Name = nameof(OrderNumber))]
        public string OrderNumber { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Display(Name = nameof(ScheduledLoading))]
        public DateTime ScheduledLoading { …
Run Code Online (Sandbox Code Playgroud)

c# reflection ef-core-2.2

0
推荐指数
1
解决办法
247
查看次数

Kotlin无法通过反射访问委托的方法:“ java.lang.NoSuchMethodException”

我试图了解反思如何与委派一起工作,并且提出了一个玩具示例。


class Foo(val m: MutableList<Any>) : MutableList<Any> by m{
}



fun fooAdd(f: Foo) {
    val a = f::class.java.getMethod("add").invoke(f, 20);
    println(a)
}

fun main(args: Array<String>) {
    fooAdd(Foo(mutableListOf()))
}
Run Code Online (Sandbox Code Playgroud)

这给我一个错误:

Exception in thread "main" java.lang.NoSuchMethodException: Foo.add()
Run Code Online (Sandbox Code Playgroud)

我不知道我理解为什么它的发生,看到 add()被委派给FooMutableList如果我理解正确。

如何解决此错误?另外,是否有一个应该用于这种用例的库?

reflection delegation kotlin

0
推荐指数
1
解决办法
152
查看次数