gpt4 book ai didi

Java : method that takes in argument any attribute of any class

转载 作者:行者123 更新时间:2023-12-01 23:15:20 25 4
gpt4 key购买 nike

我需要创建一个接受参数任何类的任何属性的方法。但我不希望它是 String 类型,以避免重命名属性时出现重构问题,并在 Eclipse 的 Markers 选项卡中获取错误,而不是在运行我的应用程序时出现错误。

有一个类人:

public class Person {

private String name;
// other attributes...

// getters and setters...

}

现在需要的方法:

void getAnAttributeOfAClass( <which_type_or_class_here?> attr_as_arg){

// Now I need to get the name of attribute that would be of class Strin...

}

是否有一个函数或方法可以让我们指定一个属性?

例如:

Person.class.name

它属于属性(property)类吗?

编辑

更准确地说(@Smallhacker 的回答帮助了我),我需要在编译时验证参数是否确实是指定类的属性。

Person.class.name // no compile time error
Person.class.nameXXX // compile time error

最佳答案

最接近您想要的是Reflection API的Field或JavaBeans Introspector API的PropertyDescriptor

但通常 Java 项目中不需要这样的东西,因为有一些库可以处理这些问题。

您可以传递一个 Class 对象以及一个 String 名称,然后让您的方法在内部使用 Introspector 来读取该属性。

关于Java : method that takes in argument any attribute of any class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21311210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com