I'm trying to create a class with static variables, but I'm not sure how to set the variables before runtime. This is what I'm attempting to do...
public class Defaults {
public static String[] abc = new String[2];
public static void functionToExecuteBeforeRuntime{
abc[0] = "a";
abc[1] = "b";
abc[2] = "c";
}
}
It's supposed to set abc
using functionToExecuteBeforeRuntime
before runtime so other classes can access it with Defaults.abc
,however it is never executed. How can I achieve this? Any help appreciated
-oh i'm not sure if th开发者_如何学运维is makes a difference but I don't think with andriod I can use the public static main()
guy
For that example, you could just initialize it there, like:
public static String[] abc = new String[]{"a", "b", "c"};
For just a general way of doing complex initialization for your static fields, I'm not sure, but I believe Android has Static Initializer Blocks, which work like:
public class Test
{
public static String[] stuff = new String[2];
static
{
stuff[0] = "Hi";
stuff[1] = "Bye";
}
}
Or you could use static functions to do, basically, the same thing.
public class Test
{
public static String[] stuff = initializeStuff();
public static String[] initializeStuff()
{
String[] arr = new String[2];
arr[0] = "Hi";
arr[1] = "Bye";
return arr;
}
}
Put it into a static initialization block of code like so:
private static String[] stuff;
static {
stuff = new String[] {"1", "2"};
}
精彩评论