This: Cannot Use This in Static Context

this: Cannot use this in static context

See, "this" keyword refers to current object due to which method is under exceution. As, you cannot call static method using instance of class. That is why, "this" can't be used in the above example in a static method as it is trying to print current instance wich is not at all created. So, I think thats why there is an compile time error that you are getting.

Cannot use 'this' in static context

You have defined a static method here :

  public static long addContact(String name, String email)

Static methods and class variables are tied to the Class and not to any specific instance of the Class. You cannot use the this keyword inside it as it refers to the current instance. One of the choice will be to declare the method as instance method removing the static keyword from the method declaration, if indeed the method logic depends on the state of the current instance.

I believe the problem in using this inside a static method will be that during runtime if your code calls the static method as ClassName.staticMethodName() , the runtime will have no idea how to resolve this in this context.

Need help using 'this' - cannot use in a static context

In the line : g2d.drawImage(image,trans,this);, the this refers to an instance of a the class that defines updateBuffer. Since updateBuffer is declared static, it cannot use a reference this, as this is not guaranteed to be initialized.


Update

public class Foo {
public Foo() {
...
}

public static void updateBuffer(Image image, int XPos , int YPos , int Height , int Width , int Rotation, AffineTransform trans, Foo foo) {
trans.translate(XPos,YPos);
trans.rotate(Rotation); //More lines will probably be more lines totransform the shape more as the game gets more advanced
g2d.drawImage(image,trans,foo); // <-- 'foo' stands in for 'this'

}

public static void main(String[] args) {
Image i = new Image();
int x,y,h,w,r;
AffineTransform t = new AffineTransform();
Foo f = new Foo();
Foo.updateBuffer(i,x,y,h,w,r,t,f);
}
}

Java 8 stream Cannot use this in a static context

There are several issues with your code. While this::compareAttrValueCountEntry would be easy to
fix by changing it to ContainingClassName::compareAttrValueCountEntry, this method is unnecessary
as there are several factory methods like Map.Entry.comparingByKey, Map.Entry.comparingByValue,
Comparator.reversed and Comparator.thenComparing, which can be combined to achieve the same goal

This guards you from the errors made within compareAttrValueCountEntry. It’s tempting to compare int
values by subtracting, but this is error prone as the difference between two int values doesn’t always
fit into the int range, so overflows can occur. Also, negating the result for reversing the order is
broken, as the value might be Integer.MIN_VALUE, which has no positive counterpart, hence, negating it
will overflow back to Integer.MIN_VALUE instead of changing the sign.

Instead of looping via forEach to add to another map, you may use a cleaner stream operation producing
the map and you can simplify sorted(…).findFirst() to min(…) which in not only shorter, but a
potentially cheaper operation.

Putting it together, we get

Map<Integer, String> attrIdMaxValueMap =
attrIdAttrValueCountMap.entrySet().stream()
.filter(e -> !e.getValue().isEmpty())
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().entrySet().stream()
.min(Map.Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey())).get().getKey()));

Note that I prepended a filter operation rejecting empty maps, which ensures that there will always be
a matching element, so there is no need to deal with ifPresent or such alike. Instead, Optional.get
can be called unconditionally.

Since this method is called findIdMaxValue, there might be a desire to reflect that by calling max
on the Stream instead of min, wich is only a matter of which comparator to reverse:

Map<Integer, String> attrIdMaxValueMap =
attrIdAttrValueCountMap.entrySet().stream()
.filter(e -> !e.getValue().isEmpty())
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().entrySet().stream()
.max(Map.Entry.<String, Integer>comparingByValue()
.thenComparing(Map.Entry.comparingByKey(Comparator.reverseOrder())))
.get().getKey()));

Unfortunately, such constructs hit the limitations of the type inference, which requires us to either,
use nested constructs (like Map.Entry.comparingByKey(Comparator.reverseOrder()) instead of
Map.Entry.comparingByKey().reversed()) or to insert explicit types, like with
Map.Entry.<String, Integer>comparingByValue(). In the second variant, reversing the second comparator,
we are hitting the litimation twice…

In this specific case, there might be a point in creating the comparator only once, keeping it in a variable and reuse it within the stream operation:

Comparator<Map.Entry<String, Integer>> valueOrMinKey
= Map.Entry.<String, Integer>comparingByValue()
.thenComparing(Map.Entry.comparingByKey(Comparator.reverseOrder()));

Map<Integer, String> attrIdMaxValueMap =
attrIdAttrValueCountMap.entrySet().stream()
.filter(e -> !e.getValue().isEmpty())
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().entrySet().stream().max(valueOrMinKey).get().getKey()));

Why can't we use 'this' keyword in a static method

Because this refers to the object instance. There is no object instance in a call of a static method. But of course you can access your static field (only the static ones!). Just use

class Sub {
static int y;
public static void foo() {
y = 10;
}
}

If you want to make sure you get the static field y and not some local variable with the same name, use the class name to specify:

class Sub {
static int y;
public static void foo(int y) {
Sub.y = y;
}
}

Cannot make a static reference / Cannot use this in static context Dilemma

Recommended way would be to make utility methods like sendQuestion static in a different class and send the context as a parameter to the method. In that way you can access this method from any where and you just need to pass the context as additional parameter to the method.

cannot access non static method GetComponent in static context, despite me not declaring the class as static

Whatever script creating the instance of the _move class (This is bad naming btw, it should be Move) should also pass its gameObject to the constructor.

// attributes here are not valid if your class is not a MonoBehaviour
public class Move
{
GameObject m_object;
public Move(GameObject obj, ...)
{
m_object = obj;
}
}

if your class is meant to be a MonoBehaviour component, then it has a GameObject member already and you can use the attributes:

[RequireComponent(typeof(BoxCollider2D),typeof(Rigidbody2D))]
// Start is called before the first frame update
public class Move : MonoBehaviour
{
void Start()
{
Debug.Log(gameObject.name);
}
}


Related Topics



Leave a reply



Submit