001    package railo.runtime.reflection.storage;
002    
003    import java.lang.reflect.Field;
004    import java.util.WeakHashMap;
005    
006    import railo.runtime.type.Struct;
007    import railo.runtime.type.StructImpl;
008    
009    /**
010     * Method Storage Class
011     */
012    public final class WeakFieldStorage {
013            private WeakHashMap map=new WeakHashMap();
014            
015            /**
016             * returns all fields matching given criteria or null if field does exist
017             * @param clazz clazz to get field from
018             * @param fieldname Name of the Field to get
019             * @return matching Fields as Array
020             */
021            public Field[] getFields(Class clazz,String fieldname) {
022                    Object o=map.get(clazz);
023                    Struct fieldMap;
024                    if(o==null) {
025                            fieldMap=store(clazz);
026                    }
027                    else fieldMap=(Struct) o;
028                    
029                    o=fieldMap.get(fieldname,null);
030                    if(o==null) return null;
031                    return (Field[]) o;
032                    
033            }
034    
035    
036            /**
037             * store a class with his methods
038             * @param clazz
039             * @return returns stored Struct
040             */
041            private StructImpl store(Class clazz) {
042                    Field[] fieldsArr=clazz.getFields();
043                    StructImpl fieldsMap=new StructImpl();
044                    for(int i=0;i<fieldsArr.length;i++) {
045                            storeField(fieldsArr[i],fieldsMap);
046                    }
047                    map.put(clazz,fieldsMap);
048                    return fieldsMap;
049            }
050    
051            /**
052             * stores a single method
053             * @param field
054             * @param fieldsMap
055             */
056            private void storeField(Field field, StructImpl fieldsMap) {
057                    String fieldName=field.getName();
058                    Object o=fieldsMap.get(fieldName,null);         
059                    Field[] args;
060                    if(o==null) {
061                            args=new Field[1];
062                            fieldsMap.setEL(fieldName,args);
063                    }
064                    else {
065                            Field[] fs = (Field[]) o;
066                            args = new Field[fs.length+1];
067                            for(int i=0;i<fs.length;i++) {
068                                fs[i].setAccessible(true);
069                                    args[i]=fs[i];
070                            }
071                            fieldsMap.setEL(fieldName,args);
072                    }
073                    args[args.length-1]=field;
074            }
075    
076    }