Is there any way to use this keyword inside a static method in Java? I want to display a Toast message inside a static method in my activity class. How do I do that? Thanks.
Now what?
static void thisInStatic(){
new Object(){
Object instance = this;
};
}
You can create a static method with one input parameter that is the Class you need to use.
For example:
public static void showMyTouch(MyActivity act, String message){
Toast.makeText(act, message, Toast.LENGTH_LONG).show();
}
No. There is nothing for it to refer to.
I believe that "this" represents the object that invokes the method. Static methods are not specifically bound to any particular object. Rather, they are class level methods. That is why "this" cannot be used in static methods.
this refers to instance members and static method will only access static variable
This refers to the object that will be created. You can't access such object from staitc method. Put you attention on it. Here some useful link to you http://mindview.net/Books/TIJ4
Related
I'm trying to call the static method getPod in the class DropPod from another class with DropPod.getPod() except I need a parameter for DropPod.getPod().
How do I change the getPod method so I can access it from the other class?
I know I could just make land() static, but I don't want to do that. I'd like to try to learn to do it this way.
public class DropPod {
protected static boolean opened;
int pos = Random.NormalIntRange(1777, 1794);
public static void getPod(DropPod drop)
{
drop.land();
}
public void land() {
Level.set(pos, Terrain.DROPPOD_CLOSED);
Game.updateMap(pos);
opened = false;
Dungeon.observe();
}
}
Option 1: You can create a new instance of DropPod in your other class. With this instance, you can just call Object.getPod().
Option 2: You already mentioned this, but you could make land a static method as well and DropPod.getPod() should work.
Static methods of a class cannot reference non-static methods of its objects.
If you only want 1 instance of DropPod, you can add it as a property of it's own class. Something like a Singleton Pattern.
Add a non-static overload for getPod() with no parameters, that just calls land().
Maybe remove the static version completely. Hard to see why this method exists at all actually, or why it is called getPod() when it doesn't return anything. I would remove it and just call land() directly.
Also hard to see why you want to call a method that calls land() when you don't have anything to land. You need to rethink all this.
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");
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(","));
}
}
}
public class CallingStaticMethod {
public static void method() {
System.out.println("I am in method");
}
public static void main(String[] args) {
CallingStaticMethod csm = null;
csm.method();
}
}
Can someone explain how the static method is invoked in the above code?
It's been optimized away by the compiler, simply because having an instance of the class is not necessary. The compiler basically replaces
csm.method();
by
CallingStaticMethod.method();
It's in general also a good practice to do so yourself. Even the average IDE would warn you about accessing static methods through an instance, at least Eclipse does here.
Java allows you to use a Class instance to call static methods, but you should not confuse this allowance as if the method would be called on the instance used to call it.
instance.method();
is the same as
Class.method();
The java language specification says the reference get's evaluated, then discarded, and then the static method gets invoked.
15.12.4.1. Compute Target Reference (If Necessary)
This is the same behavior when you use the this reference to call a static method. this gets evaluated then discarded then the method is called.
There is even an example in the specification similar to your example.
When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null:
class Test1 {
static void mountain() {
System.out.println("Monadnock");
}
static Test1 favorite(){
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
favorite().mountain();
}
}
Well this is perfectly ok. The static method is not being accessed by the object instance of class A. Either you call it by the class name or the reference, the compiler will call it through an instance of the class java.lang.Class.
FYI, each class(CallingStaticMethod in the above illustration) in java is an instance of the class 'java.lang.Class'. And whenever you define a class, the instance is created as java.lang.Class CallingStaticMethod = new java.lang.Class();
So the method is called on 'CallingStaticMethod ' and so null pointer exception will not occur.
Hope this helps.
Yes we can.
It will throw NullPointerException only if we are calling non static method with null object. If method is static it will run & if method is non static it will through an NPE...
To know more click here...
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);