Java 反思:检查对象是否已经创建

Java Reflection : check if object is already created

   BeanInfo componentBeanInfo = null;
   List<String> propNames =new ArrayList<String>();
   Object nestedObject=null;
            try {
            componentBeanInfo = Introspector.getBeanInfo(sourceObject.getClass());  
            final PropertyDescriptor[] props=componentBeanInfo.getPropertyDescriptors();
            String [] parameters = getParameters(); //ObjectA.code="abc",ObjectA.type="single"
            for (String parameter : parameters) {
                boolean isNestedField = isNestedPropertyRead(parameter);
                for(PropertyDescriptor prop : props){
                    if(isNestedField){
                        String[] fullParam = parameter.split("\.");//ObjectA.code
                        String nestedObj = fullParam[0];//ObjectA
                        String nestObjField = fullParam[1];//code
                        if(nestedObj.equalsIgnoreCase(prop.getName())){
                            Class<?> classType = Class.forName(prop.getPropertyType().getName());                       
                            BeanInfo nestedBeanInfo;
                            nestedBeanInfo = Introspector.getBeanInfo(classType);
                                final PropertyDescriptor[] nestedProps =nestedBeanInfo.getPropertyDescriptors();
                                    for(PropertyDescriptor nestedProp : nestedProps){
                                        if(nestedProp.getName().equalsIgnoreCase(nestObjField)){
                                            Class<?> nestedClassType = Class.forName(nestedProp.getPropertyType().getName());
                                            Object value = convertToObject(nestedClassType,value(parameter));
                                            try {                                       
                                                /*if(isNewProperty(prop.getName(),propNames)){
                                                 nestedObject = classType.newInstance();
                                                }*/
                                                if(nestedObject == null) {
                                                nestedObject  = classType.newInstance();
                                                }
                                                nestedProp.getWriteMethod().invoke(nestedObject, value);
                                                prop.getWriteMethod().invoke(sourceObject,nestedObject );
                                            } catch (IllegalArgumentException | InstantiationException | InvocationTargetException e) {
                                                e.printStackTrace();
                                            }
                                          break;
                                        }
                                    }
                            break;
                        }
                    }
                    else if(prop.getName().equalsIgnoreCase(parameter)){                    
                        try {
                            Class<?> classType = Class.forName(prop.getPropertyType().getName());
                            Object value = convertToObject(classType,value(parameter));
                            prop.getWriteMethod().invoke(sourceObject, value);
                            break;
                        } catch (IllegalArgumentException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }   
      }catch (IntrospectionException | IllegalAccessException e) {
            e.printStackTrace();
      }

In above code snippet I'm facing issue w.r.t following lines -

    nestedObject  = classType.newInstance();

This creates new Instance every time and because of which i end up up setting values to new nested objects each time overriding the previous object. How can i avoid this and set values to already created object in loop. Can anyone please suggest how can i get it working?

I'll definitely be changing below piece of code also as generic one rather than limiting to one instance of ' . ' as delimiter.But thought of getting the looping logic right first.

String[] fullParam = parameter.split("\.");//ObjectA.code
String nestedObj = fullParam[0];//ObjectA
String nestObjField = fullParam[1];//code

UPDATE-1- @javaguy - My object structure looks like below-

public class OuterObject {

private String field1;

private ObjectA field2;

private ObjectB field3;

private String  field4;

...// can have lot of nested objects of different types like ObjectA,ObjectB etc

}

public class 对象 A {

private String field1;

private int field2;

private String field3;

...

}

public class 对象 B {

private String field1;

private String field2;

private String field3;

...

}

As per your logic, nestedObject will have instance of ObjectA when ObjectA's field (say field2) is encountered first.When we get ObjectB's field next (say field1) we check if nestedObject is null and since it is not null we don't create new instance for ObjectB.Because of this we end up setting ObjectB's field value (field1) in ObjectA in following line- nestedProp.getWriteMethod().invoke(nestedObject, value); This results in error - java.lang.IllegalArgumentException: object is not an instance of declaring class

您需要在循环外声明 Object nestedObject=null;,然后通过检查实例是否为 null 来仅创建一次实例,如下所示:

if(nestedObject == null) {
    nestedObject  = classType.newInstance();
}

I could make it work after adding following lines of code -

Object nestedObject = prop.getReadMethod().invoke(sourceObject);                                            
if(nestedObject == null){
        nestedObject  = classType.newInstance();    
}