How to get string value from a Java field via reflection?

后端 未结 5 598
北海茫月
北海茫月 2020-12-09 16:28

I have a method:

public void extractStringFromField(Class classToInspect) {
    Field[] allFields = classToInspect.getDeclaredFields();

    for(Fie         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 17:09

    Just had the same issue. This Thread somewhat helped. Just for reference if somebody else stumbles upon this thread. I used the StringBuilder class to convert so basically:

    StringBuilder builder = new StringBuilder();
    builder.append(field.get(object))
    

    Which has multiple advantages. One that you do not explicitly cast (which btw. causes problems with primitive types int vs. Integer) but also of being more efficient if you have multiple string operations sequentialy. In time critical code parts.

提交回复
热议问题