简体   繁体   English

Java Servlet静态类

[英]Java Servlet Static Class

I'm learning J2EE and migrating my ASP.NET project into Java. 我正在学习J2EE,并将ASP.NET项目迁移到Java。

IN Asp.NET I have Helper class which has methods like encode decode, convert, etc... 在Asp.NET中,我有Helper类,该类具有诸如编码解码,转换等方法。

In ASP.NET I'm initiating public static class Helper as separate cs file and then I'm calling this static class from code behind when ever I need it. 在ASP.NET中,我将公共静态类帮助程序作为单独的CS文件启动,然后在需要时从代码后面调用此静态类。

Helper.Parse();
Helper.Convert();

etc.... 等等....

How can I achieve the same functionality in Servlet/JSP project? 如何在Servlet / JSP项目中实现相同的功能?

Just as an addition to what PeterMmm said, it is good practice with such classes which merely exist to group static methods, to enforce non-instantiability of the class. 正如PeterMmm所说的那样,对此类类的优良作法是仅将静态方法分组以强制该类的非实例性。 To achieve this, you can provide only a private default (no arguments) constructor, which does nothing but throw an AssertionError. 为此,您只能提供一个私有的默认(无参数)构造函数,该构造函数除了抛出AssertionError外什么也不做。 This prevents instantiation both inside and outside the class. 这样可以防止在类的内部和外部进行实例化。

This technique is something I learned from Effective Java, and is available in a sample chapter at: 这种技术是我从有效Java中学到的,可以在以下示例章节中找到:

http://www.informit.com/articles/article.aspx?p=1216151&seqNum=4 http://www.informit.com/articles/article.aspx?p=1216151&seqNum=4

That said, I do recommend the whole book if you're moving to Java and want to learn about best practices and how exactly they improve your code. 就是说,如果您要使用Java,并且想了解最佳实践以及它们如何精确地改进您的代码,我确实会推荐整本书。

In Java it is straigt the same you will define a class Helper with only public static methods. 在Java中,与仅使用公共静态方法定义类Helper的方法相同。

package my.proyect;

public class Helper {

    public static void Parse() {
        // your code 
    }
}

Maybe it is a good deal then to rename to Java name conventions . 然后重命名为Java名称约定可能是一件好事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM