获取声明的方法,以便它们出现在源代码中 [英] Get declared methods in order they appear in source code

查看:44
本文介绍了获取声明的方法,以便它们出现在源代码中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种情况似乎不正常,但是我被要求构建序列化程序,该序列化程序将通过"get"方法的连接结果将一个对象解析为字符串.这些值的显示顺序应与在源代码文件中声明的"get"等效项的顺序相同.

The situation seems to be abnormal, but I was asked to build serializer that will parse an object into string by concatenating results of "get" methods. The values should appear in the same order as their "get" equivalent is declared in source code file.

例如,我们有

 Class testBean1{
  public String getValue1(){
   return "value1";
  }

  public String getValue2(){
   return "value2";
  }
 }

结果应为:

"value1 - value2"

不是

"value2 - value1"

根据文档,不能使用 Class 对象完成此操作.但是我想知道是否可以在"* .class"文件中找到此信息,还是丢失了?如果存在此类数据,也许有人知道为此目的准备使用的工具?如果找不到此类信息,请提出实现目标的最专业方法.我曾考虑过将一些自定义注释添加到应该序列化的类的getter中.

It can't be done with Class object according to the documentation. But I wonder if I can find this information in "*.class" file or is it lost? If such data exists, maybe, someone knows a ready to use tool for that purpose? If such information can't be found, please, suggest the most professional way of achieving the goal. I thought about adding some kind of custom annotations to the getters of the class that should be serialized.

推荐答案

尽管反射不再存在(我认为从Java 7开始)按照源代码中出现的顺序为您提供了方法,但类文件却出现了仍然(从Java 8开始)按其在源代码中出现的顺序包含这些方法.

Although reflection does not anymore (as of java 7 I think) give you the methods in the order in which they appear in the source code, the class file appears to still (as of Java 8) contain the methods in the order in which they appear in the source code.

因此,您可以解析类文件以查找方法名称,然后根据在其中找到每个方法的文件偏移量对方法进行排序.

So, you can parse the class file looking for method names and then sort the methods based on the file offset in which each method was found.

如果您想以一种不太客气的方式进行操作,可以使用Javassist,它会为您提供每个已声明方法的行号,因此您可以按行号对方法进行排序.

If you want to do it in a less hacky way you can use Javassist, which will give you the line number of each declared method, so you can sort methods by line number.

这篇关于获取声明的方法,以便它们出现在源代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆