我想知道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运营商有可能吗?
使用:
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) 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!
编辑:
这个问题不是关于变通方法或替代方法.所以答案不是解决方法.对于其他方式,请参阅下面的回答.
给定一个结构的任意实例,我希望能够执行所有不接受参数的公共方法.
例如,在下面的代码中,我希望能够执行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) 所以我有一个抽象的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) 我想动态创建以下表达式:
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'与提供的类型参数和参数兼容.如果方法是非泛型的,则不应提供类型参数.
简单- 找 -问题,但我开始想我想要实现的东西走错了路.假设我有一个Method正确初始化的对象.
我需要检查该方法是否会返回实现该Comparable接口的对象.
问题是method.getReturnType()返回一个Class<?>对象,我想检查一下这个"?" 实际上是可比较的实例,但我不能写? instanceof Comparable,怎么会这样做呢?
编辑:我知道我可以做result = method.invoke(someObject),然后result instanceof Comparable我需要在我更大的对象的构造函数中进行这些检查,如果我清楚的话,不知道.
如何获取函数的返回值长度,效果类似如下:
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功能或平等的功能?
我想在我的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) 我试图了解反思如何与委派一起工作,并且提出了一个玩具示例。
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()被委派给Foo从MutableList如果我理解正确。
如何解决此错误?另外,是否有一个应该用于这种用例的库?
reflection ×10
java ×5
c# ×2
generics ×2
go ×2
abstract ×1
class ×1
delegation ×1
ef-core-2.2 ×1
field ×1
instanceof ×1
kotlin ×1
oop ×1
syntax ×1
type-erasure ×1