日期:2014-05-19  浏览次数:20648 次

|.NET转Java|在C#中给对像添加扩展方法,那JAVA有没有办法添加 谢谢
在C#中要给字符串添加一个过滤掉HTML内容的扩展方法为
C# code

    /// <summary>
    /// 过滤HTML成文件并删除所有HTML标记
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static string FilterHtml(this string source)
    {
        if (source != null && source.Length > 0)
        {
            source = System.Text.RegularExpressions.Regex.Replace(source, "<[^>]*>", "");
            source = source.Replace("&nbsp;", " ");
            source = source.Replace("<br/>", "\r\n");
        }
        return source;
    }


然后对字符就可以用
C# code

    public void Test()
    {
        string html="我是<b>组体</b>";
        string result = html.FilterHtml();
        System.Console.Write(result);
        //结果为:我是粗体
    }


上面是C#给字符串添加扩展方法的代码,不知道Java有没有这人功能
如果有,如何来实现?

谢谢

------解决方案--------------------
写静态函数吧……这个不过是语法糖而已
------解决方案--------------------
Java code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String html = "我是<b>粗体</b>";
        String result = FilterHtml(html);
        System.out.println(result);
    }

    // / <summary>
    // / 过滤HTML成文件并删除所有HTML标记
    // / </summary>
    // / <param name="source"></param>
    // / <returns></returns>
    public static String FilterHtml(String source) {
        if (source != null && source.length() > 0) {
            Pattern pattern = Pattern.compile("<[^>]*>");// 用指定的正则表达式进行预编译

            Matcher matcher = pattern.matcher(source);// 创建匹配给定输入与此模式的匹配器。
            StringBuffer sbf = new StringBuffer();
            while (matcher.find()) {// 描输入序列以查找与该模式匹配的下一个子序列。
                // System.out.println(sbf.toString());
                matcher.appendReplacement(sbf, "");//
            }
            matcher.appendTail(sbf);
            source = sbf.toString();

            source = source.replaceAll("&nbsp;", " ");
            source = source.replaceAll("<br/>", "\r\n");
        }
        return source;
    }

}

------解决方案--------------------
探讨

我想到一个方法了,
但不知道可行不可行
JAVA不就是开源的吗?
那我可以他的源代码上面把我想要添加的方法加上去
然后再重新编辑出一个我自己的Java?
这样可行不可行啊?