简体   繁体   中英

Java Servlet Static Class

I'm learning J2EE and migrating my ASP.NET project into Java.

IN Asp.NET I have Helper class which has methods like encode decode, convert, etc...

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.

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

etc....

How can I achieve the same functionality in Servlet/JSP project?

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. To achieve this, you can provide only a private default (no arguments) constructor, which does nothing but throw an 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:

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.

In Java it is straigt the same you will define a class Helper with only public static methods.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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