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(","));
}
}
}
Related
I got into programming a bit obliquely with Bukkit and thus didn't learn some things properly. But since I've been doing real stuff for a while now I wanted to ask how to deal with static.
I know that you should avoid static as most as possible.
Should you then call external functions like this?
//Another Class
public void exampleMethodInAnotherClass() {
system.out.prinln("Hi :D");
}
//Main
public static void main(String[] args) {
new AnotherClass().exampleMethodInAnotherClass();
}
//OR
public static void exampleMethodInAnotherClass() {
system.out.println("Hi :D");
}
public static void main(String[] args) {
AnotherClass.exampleMethodInAnotherClass();
}
Now it's about the type of function that you use if the function is too much used in your code like System.out.println then make it static *(static function are mostly common in maths and helper classes).
OH the static keyword , My most hero in the programming!
I know that you should avoid static as most as possible.
no that's not true in the most cases the programmer that are student or new in the programming think it's best Idea that we have use static key but it's important to know the why we use static.
after you use static key the variable imidediately going to memory and you can accsess it directly by calling the refrence! and it's the package and class with the variable name but the static method is in the memory and if you change it from some where in your code the data change , see some example :
public class Test {
static String MESSAGE= "";
public static setMessage(String message){
MESSAGE = message;
}
public static void showMessage(){
System.out.println(MESSAGE);
}
}
----------------
Calling from another class
public static void showMessage(){
System.out.println(Test.MESSAGE);
}
if you run the program and change the message with the showMessage method you can get the message and if you need you can call the MESSAGE by reference Like ClassName.MESSAGE or create object from your class with new Keyword but your MESSAGE variable is static and in your memory after running your code so the use new keyword to call it not nesssasery and you can call it directly ! remember using the static variable in mini or script cases or test is good idea but if you create Enterprise project using static method or variable without knowledge about it it's bad idea! because , I most use static keyword for method or variable I need always return same result or work straight work I need! like show the time , convert date or etc... but don't use for changing the data The example I share it's good ref for know the problem.
Good ref for know the static internal work it's here
This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
For some reason when I'm trying to call methods using a main method or try changing variables declared outside the main method I get forced into having to change everything to static. This is fine in places but when it comes to needing to change values later in the code for example using a Scanner for input the main method just takes it to a whole new level trying to make me change the Scanner library etc.
This example shows what happens if I try calling a method.
This example shows what happens when I try alter the value of a variable declared outside my main method.
I have never faced an issue like this before when writing java code I've tried recreating the classes/ project files etc but nothing works. I've tried looking everywhere for a solution but I can't seem to find one probably due to the fact that I don't know what to search for. I've probably made myself look like a right idiot with my title haha! Any suggestions people?? Thanks in advance!
Maisy
It can be a bit confusing to get out of "static land" once you are in your main() method. One easy way is to have another object contain your "real" (non-static) top level code and then your main method creates that object and starts it off.
public static void main() {
MyEngine engine = new MyEngine();
// core logic inside of start()
engine.start();
}
I hope that this was clear enough for you. Good luck Maisy!
When calling methods form a main you have to instantiate the class they are in, unless it's a static function
this is because that a class is a sort of template and there is nothing saved about it before it get instantiated
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
}
public method method(){}
}
in the example above i instantiated a TestClass and then called on the testClass instance
there is some functions and variables on classes you might want static, because a static on a class is shared between ALL instances, and can be called on the class, say you want to know how many instances were created then something like this can be done.
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
System.out.print(TestClass.instances +""); // note that i call on
//the class and not on an instance for this static variable, and that the + ""
//is to cast the int to a string
}
public static int instances = 0; // static shared variable
public TestClass(){instances++;} // constructor
public method method(){}
}
You need to do some Object Oriented Programming tutorial and to learn some basic.
As answer for your problem to call without using static you have to create an instance of the main Class
let suppose the following class Foo
public class Foo{
private int myVarInteger;
public int getMyVarInteger(){ return this.myVarInteger;}
public void setMyVarInteger(int value){this.myVarInteger = value;}
public static void main(String[] args){
Foo myClassInstanceObject = new Foo();
// now we can access the methods
myClassInstanceObject.setMyVarInteger(5);
System.out.println("value ="+myClassInstance.getMyVarInteger());
}
}
I want to declare a factory class with some methods and attributes that can be used like this:
ClassFactory myObj = MyObj("Class1").method1("input 2");
It seems that this is not a valid JAVA statement because JAVA is fully Object oriented and don't let to declare global function. But if there are a mechanism that let define function without name we can define it as a static function and use it as mentioned above.
Is there any way to implement that in JAVA in that manner or any other way?
You can create a public static method in a class and it can be use globally. For instance a method public static boolean doesWork() { return true; } in a public class named GlobalClass can be accessed by GlobalClass.doesWork() and would return true.
Thanks to Sotirios Delimanolis for Help:
this is possible with defining the static method and import it statically in every where you want.
package factorypakcage;
public class firstFactory{
public static factoryFunction(String className){
//switch case for class creation
}
}
Using like this
import static factorypakcage.firstFactory.factoryFunction;
...
MyClass MyObj = factoryFunction("Class Name");
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 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);