문제

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