Java 怎么搜索ID与正则表达式匹配的JSF组件

2019年8月14日22:08:07Java 怎么搜索ID与正则表达式匹配的JSF组件已关闭评论 141 1088字阅读3分37秒

1.简介

Java 怎么搜索ID与正则表达式匹配的JSF组件?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import javax.faces.component.UIComponent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main{
    
     
    public static <S extends UIComponent> S findFirstComponentByRegEx(
            UIComponent baseComponent, final String regex) {
        final List<S> results = new ArrayList<>();
        recurseChildren(baseComponent, 0, new UIComponentVisitor() {
            @Override
            public boolean visit(UIComponent component, int depth) {
                if (component.getId() != null
                        && component.getId().matches(regex)) {
                    results.add((S) component);

                    
                    
                    return false;
                }

                
                return true;
            }
        });

        
        return (results.size() > 0 ? results.get(0) : null);
    }
    
    public static boolean recurseChildren(UIComponent baseComponent,
            int depth, UIComponentVisitor visitor) {
        if (visitor.visit(baseComponent, depth) == false) {
            
            return false;
        }

        if (baseComponent.getFacetsAndChildren() != null) {

            Iterator<UIComponent> childComponentIterator = baseComponent
                    .getFacetsAndChildren();
            while (childComponentIterator.hasNext()) {
                UIComponent childComponent = childComponentIterator.next();
                if (recurseChildren(childComponent, depth + 1, visitor) == false) {
                    
                    return false;
                }
            }
        }

        
        return true;
    }
}

 
继续阅读
编程十万个怎么办