I would like to know the easier way to access a function from any file that I want

For example i got this function :

public String MD5(String md5) {
   try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(md5.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
          sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
       }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    }
    return null;
}

I want this function to be called from every files .java that I got, how to do that?

有帮助吗?

解决方案 2

if you declare the function in a public class, you can access it anywhere you want. if that function was in Utils.java,

public class Utils {
  public static String MD5(...) { ... };
}

from any other class, you could access it like,

String s = Utils.MD5(...);

其他提示

IF this function only relies on the input provided and returns back the same output for the same input irrespective of the state of the program, then you should make it static :

 public static String MD5(String md5) {
    // do something
 }

Then this function can be accessed form any class as follows :

  String md5Val = Utils.MD5("my string");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top