Sorry, new to Java.
I have a code like this:
public class abc implements xyz {
private final static ABCParameters defaultAbcParameters = ABCParameters.newBuilder()
....
....
.build();
...
...
}
ABCParameters is a google protobuf message, and we have the generated JAVA code for that.
Is there any possibility for defaultAbcParameters to be null? Wouldn't this be initialized when the class gets loaded?
How is this way of initialization different from initializing in the constructor?
Thanks for your time.
Yes, if the builder returns null.
The difference is that your variable is static so it is shared by all the instances of the abc class. If you would initialise in the constructor, then the variable wouldn't be static anymore and it would be one per class instance.
Related
I have a class as follows:
public class MyClass {
...
String lang = Config.getLang();
...
}
Config.getLang() is a public static method in class named Config. My question is: Does this initialization have any implication or problem?
String lang = Config.getLang();
Eclipse does not report any compilation problem.
As posted and described (and in general) it's perfectly valid to initialize a field by calling a static method (even if that method is in another class).
If I am not wrong, how many ever same Strings are created, only in only place it is stored by using String interning. If so, what is the use of making a Sting static if it is already being stored in only one place in memory which is nothing but acting as if it was a static variable. Thanks.
Static Strings can be accessed outside the class without creating the class's variable. Example of this is:
public class Stuff {
public static final String foo = "foo";
}
Here is an example of calling the variable foo (while still retaining it's contents of foo):
public class Application {
public static void main(String[] args) {
System.out.println(Stuff.foo);
}
}
As mentioned, I did not have to initialize Stuff in Application.
If you want to access it staticly outside of a class without initializing the class, then you make it static
You may want a class to access that String value but you do not want to initialize the class which holds the String. This is useful if one class is using the String but not using the rest of the class that holds the String.
I want to store an object state between activities (already considered Parcelables, JSON, yadda yadda) but since I have a couple of Singletons, might as well refer to them in a class that extend Application (modularity + easy to maintain).
So to my question, let's say I have a simple singleton:
class SimpleSingleton
{
private static final SimpleSingleton instance; //The question will refer this line later.
public static SimpleSingleton getInstance()
{
return instance;
}
private SimpleSingleton(){}
}
1: At first I create an initInstance() method within the above class, e.g:
class SimpleSingleton
{
//... the code above
public static void initInstance()
{
if(instance == null) instance = new SimpleSingleton();
}
}
2: Hence the below works, (in which afterwards, I can refer to the singleton from any activity via CustomSingleton.getInstance()):
class MyApp extends Application
{
#Override
public void onCreate()
{
super.onCreate();
initSingletons();
}
protected void initSingletons()
{
SimpleSingleton.initInstance();
}
}
BUT. What if I declare
private static final SimpleSingleton instance = new SimpleSingleton();
instead of
private static final SimpleSingleton instance;
in the SimpleSingleton class?
I assume the object is initialized during compile time, so doesn't that makes the whole #1 and #2 unnecessary? Or do I get the order wrong (especially WHEN the class is actually initialized)? I came from C# and currently developing for Android so this kinda gave me a quick gotcha when I want to refer to my Singletons. Also, I ask this since according to this blog:
The explanation of the weird behavior I saw that makes more sense to me is that the static variables instances are bound to the class loader of the class that first initialized them.
The only difference i can think of is when you do
private static final CustomObject instance = new CustomObject();
when you application is launched it will create and allocate space for it.
Note it might never be used but it would still be using memory.
when you create it on an onCreate method it will only create an instance when it is called.
Using static also has one more disadvantage that is it will use your perm gen space and if by chance it fails to give it space or fails to create it your program will crash on startup. Leaving you confused.
I strongly suggest using the onCreate method approach.
I'm trying to initialize a static class, with an argument, and then run some more static code in that class.
I'm aware of the static block, but it seems it can't take any arguments.
Is there a way to pass arguments to a static constructor?
If not, what is the recommended technique to initialize a Static class using an argument?
Edit:
A static class to my understanding is a class which cannot be instantiated (in c# they're called static classes, if Java has a different term for them, sorry for not being aware of it) - it's accessed through it's class name rather than an object name.
What I'm trying to achieve (very simplified) is a class which receives a dictionary as String, parses it, and has methods manipulate it like GetRandomEntry.
Here's an elaborated snippet of my code:
public class QuestionsRepository {
private static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
//...
staticĀ
{
// need to receive and parse dictionary here
}
//...
Taking the relevant parts of a code snippet is never easy, hope i have chosen wisely (:
Another detail that may be relevant - I'm a c# programmer, usually. Just Started learning Java lately.
Thanks.
I think you would need to initialize the static fields of the class according to some input. You can do it in the following way by calling the static method of another class:
class ClassToInitialize {
static {
staticField = ParamPassClass.getParameter();
}
private static String staticField;
ClassToInitialize() {
System.out.println("This is the parameter: " + staticField);
}
}
class ParamPassClass {
private static String parameter;
static String getParameter() {
return parameter;
}
static void setParameter(String parameter) {
ParamPassClass.parameter = parameter;
}
}
class Main {
public static void main(String args[]) {
ParamPassClass.setParameter("Test param");
new ClassToInitialize();
}
}
Java doesn't have static constructors. It only has static initializers and static initializers do not take any arguments. It is executed when the class is first loaded, and there is no way to call it yourself.
You either need to use actual objects, or add some way of configuring the class (eg through a static method).
you should mention the member class with a static qualifier, otherwise there is no such a thing as a static class
Here you can find the explanation of using the word 'static' in this context.
Now you should just call its constructor and pass all the arguments you want,
the only restriction that you have on a static member class is that it can't refer the non-static fields of its outer class, it resembles a static methods on class that can't refer the non-static fields of class.
I didn't understand why do you mention a static initialization block here, could you please clarify a little?
Be aware also that in java there is no such a thing as static constructor....
Hope this helps
You can have a static method public static void setUp(Arg1 arg1, Arg2 arg2...) which sets up all your static fields and invoke it when your program starts.
You have to make sure this method will be called only once [or only when you want to reset these fields]
It is not possible to pass arguments directly to the static initializes (JLS:static initializers).
It would be nice if you could share more information about your goals.
You could use an enum to initialize a singleton with a string parameter like this
import java.util.*;
class Data {
static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
}
public enum QuestionsRepository
{
repository("primary=red,green,blue;secondary=cyan,yellow,magenta");
QuestionsRepository(String dictionary) {
String[] rules = dictionary.split(";");
for (String rule:rules) {
String[] keyValuePair = rule.split("=",2);
Data.easyDefinitions.put(keyValuePair[0],keyValuePair[1].split(","));
}
}
}
I use an java application which generates a class dynamically. Via an ant script the source code will be produced for a give classname and a class template.
In the template for the class I need to know the name of even this class, to call a static method of the class.
Example. The class will be named "VersionInfo". Then in static main() of it I want to call the static method: VersionInfo.getId().
But I don't know the class-name.
Is there an equivalent to "this" for static contexts or some Utility-Class for such a purpose?
If you are creating the class via Ant then why not just generate a static method getClassName that returns the name of the class?
If your main method resides in the same class you just can call getId() in the main method.
So you're saying that it should generate this?
public class VersionInfo{ // VersionInfo class name changes, per problem description
public static void main(){
System.out.println(getId());
// but in the main within the class,we don't need the classname to call a static method
}
public static string getId(){
return "what's the problem?";
}
}
Is there something missing from the description, that you're calling some OTHER class' static method by an unknown-to-the-template name?
There's a nasty workaround:
public static final Class THIS_CLASS = new Object() {
public Class getParentClass() {
return getClass().getEnclosingClass();
}
}.getParentClass();
I'm not sure I understand. If you generate the class VersionInfo yourself, why can't you get the class name from the code that generates the class?
Try this:
package uk.co.farwell.stack_overflow;
public class Test_847708 {
private final static String getId() {
return "string";
}
public static void main(String args[]) {
System.out.println("getId=" + getId());
}
}
You cannot use the key "this" in a static context.
Instead, if you want to call dynamically a static function, you can use java reflection.
I cannot help you further for java reflection because I never use it, but I already use it in .Net and it's a powerful tools.
The cleanest answer to the question might be to make a third class with a static, known, name that is generated by the ANT script which references the dynamic class name, and then have your main method reference that known class.
If for some reason that isn't enough, then combine Joachim Sauer and Melursus answer, and get the class name, and then get the method via reflection:
Method m = THIS_CLASS.getDeclaredMethod("getId", null);
Object result = m.invoke(null, null);