如何在没有公共无参数构造函数的情况下获取 pojo 类的属性名称?

发布于 2024-10-08 01:08:15 字数 244 浏览 0 评论 0原文

我想要获取 POJO 属性名称的数组(或列表)。 我尝试了 commons-beanutil 的 BeanUtils.describe(obj) ,但它需要一个对象实例。 但是如果我只有那个类,没有公共的无参数构造函数怎么办?我无法使用 clazz.newInstance() 生成对象。

我该怎么解决呢?是否有任何库可以深入研究类并传递属性名称?

(我知道我可以使用反射来手动解析类结构,但我正在寻找一个方便的库)

谢谢。

I want to get an array(or list) of a POJO's property names .
I tried commons-beanutil's BeanUtils.describe(obj) , but it needs an object instance.
But what if I only have that class , without a public no-arg constructor . I cannot use clazz.newInstance() to generate an object.

How should I solve it ? Is there any libraries that can dig into a class and pass property names ?

(I know I can use reflection to manually parse the class structure , but I am looking for a handy library)

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

皓月长歌 2024-10-15 01:08:15

我从未使用过它(或 java.beans 中的任何内容,就此而言),但 java.beans.Introspector.getBeanInfo(Class) 可能就是您想要的寻找。

I've never used it (or anything in java.beans, for that matter), but java.beans.Introspector.getBeanInfo(Class) may be what you're looking for.

方圜几里 2024-10-15 01:08:15

Java 在反射 utils 中构建了它 - 您可以使用它。看一下 Class 的 java 文档

例如,使用反射 Demo.class.getMethods(); 获取名为 Demo 的类的所有 getter 方法(无需实例化它。)

List<Method> allGetterMethodsOfClassDemo() = new ArrayList<Method>();
for(Method method : Demo.class.getMethods()){
  if(method.getName().startsWith("get") || method.getName().startsWith("is")) {
    allGetterMethodsOfClassDemo.add(method);
  }
}

Java has its build in reflection utils - which you can use. Hava a look at the java doc of Class.

For example using reflectionDemo.class.getMethods(); to get all getter methods of a Class called Demo (without instanciating it.)

List<Method> allGetterMethodsOfClassDemo() = new ArrayList<Method>();
for(Method method : Demo.class.getMethods()){
  if(method.getName().startsWith("get") || method.getName().startsWith("is")) {
    allGetterMethodsOfClassDemo.add(method);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文