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

后端 未结 5 590
北海茫月
北海茫月 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:08

    Just usefull example code for reflection fields:

    Field[] fields = InsanceName.getDeclaredFields();
    for (Field field : fields) {      //array for fields names
    
    System.out.println("Fields: " + Modifier.toString(field.getModifiers())); // modyfiers
    System.out.println("Fields: " + field.getType().getName());  //type var name
    System.out.println("Fields: " + field.getName());        //real var name
    field.setAccessible(true);                                //var readable
    System.out.println("Fields: " + field.get(InsanceName));  //get var values  
    System.out.println("Fields: " + field.toString());     //get "String" values
    System.out.println("");  //some space for readable code
    }
    
    0 讨论(0)
  • 2020-12-09 17:09

    It looks like you need a reference to an instance of the class. You would want to call get and pass in the reference, casting the return to a String.

    You can use get as follows:

    String strValue = (String) field.get (objectReference);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-09 17:21

    In ideal situations,Class does not hold data. It merely holds the information about the structure and behavior of its instances and Instances of the Classes hold your data to use. So your extractStringFromField method can not extract values unless you pass any instances (from where it will actually extract values).

    If the name of the parameter of the reference, you are passing to extract value is instance, then you can easily get what you want like bellow:

    String strValue = (String)field.get(instance);
    
    0 讨论(0)
  • 2020-12-09 17:24
    String strValue = field.getName().toString();
    

    Full code looks like this:

    public static void extractStringFromField(Class<?> Login) {
        Field[] allFields = Login.getDeclaredFields();
    
        for(Field field : allFields) {
            String strValue = field.getName().toString();
    //          if(field.getType().isAssignableFrom(String.class)) {
                System.out.println("Field name: " + strValue);
            }
        }
    
    0 讨论(0)
提交回复
热议问题