I tried different ways to fix this, but I am not able to fix it. I am trying to get the Boolean value of an Object passed inside this method of a checkBox:
public boolean onPreferenceChange(Preference preference, Object newValue)
{
final String key = preference.getKey();
referenceKey=key;
Boolean changedValue=!(((Boolean)newValue).booleanValue()); //ClassCastException occurs here
}
I get:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
Instead of casting it, you can do something like
Boolean.parseBoolean(string);
Here's some of the source code for the Boolean class in java.
// Boolean Constructor for String types.
public Boolean(String s) {
this(toBoolean(s));
}
// parser.
public static boolean parseBoolean(String s) {
return toBoolean(s);
}
// ...
// Here's the source for toBoolean.
// ...
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
So as you can see, you need to pass a string with the value of "true" in order for the boolean value to be true. Otherwise it's false.
assert new Boolean( "ok" ) == false;
assert new Boolean( "True" ) == true;
assert new Boolean( "false" ) == false;
assert Boolean.parseBoolean( "ok" ) == false;
assert Boolean.parseBoolean( "True" ) == true;
assert Boolean.parseBoolean( "false" ) == false;
From the code you posted, and the result you are seeing, it doesn't look like newValue is a boolean. So you try to cast to a Boolean, but it's not one, so the error occurs.
It's not clear what you're trying to do. Ideally you'd make newValue a boolean. If you can't do that, this should work:
boolean newValue;
if (newValue instanceof Boolean) {
changedValue = newValue; // autoboxing handles this for you
} else if (newValue instanceof String) {
changedValue = Boolean.parseBoolean(newValue);
} else {
// handle other object types here, in a similar fashion to above
}
Note that this solution isn't really ideal, and is somewhat fragile. In some instances that is OK, but it is probably better to re-evaluate the inputs to your method to make them a little cleaner. If you can't, then the code above will work. It's really something only you can decide in the context of your solution.
If you know that your Preference is a CheckBoxPreference, then you can call isChecked(). It returns a boolean, not a Boolean, but that's probably close enough.
Here is some code from the APIDemos Device Administration sample (DeviceAdminSample.java).
private CheckBoxPreference mDisableCameraCheckbox;
public void onResume() {
...
mDPM.setCameraDisabled(mDeviceAdminSample, mDisableCameraCheckbox.isChecked());
...
}
public boolean onPreferenceChange(Preference preference, Object newValue) {
...
boolean value = (Boolean) newValue;
...
else if (preference == mDisableCameraCheckbox) {
mDPM.setCameraDisabled(mDeviceAdminSample, value);
reloadSummaries();
}
return true;
}
Related
I get an error on Eclipse when i try this code
boolean notif = (Boolean) null;
if(notif == null) // <== ERROR at this line saying "No suggestion available" (very helpful)
{
System.out.println("Notif = null");
}
Why it doesn't work ?
boolean is a primitive type, it only accepts true or false. If you want to assign null to your variable, use the object Boolean instead.
Boolean notif = null;
if(notif == null) {
System.out.println("Notif = null");
}
But... if you're using the primitive type, do this:
boolean notif = // true or false;
if(notif) {
System.out.println("Notif = true");
}
else {
System.out.println("Notif = false");
}
EDIT: The difference between Boolean and boolean is that the first one is an object, and it comes with some methods you might want to use. The second one, as a primitive type uses less memory. Now consider those points and choose what you need ;)
More on Boolean object here on the docs.
When you casting null to "Boolean it's wrapper class not the primitive boolean. but when you are comparing you are comparing with the primitive boolean which expects value only true or false not null.
boolean can't be null. It can either be true or false
boolean notif = false;
if(notif)
{
System.out.println("notif is true");
}
else
{
System.out.println("notif is false");
}
while the Object Boolean can be.
You are trying to get the value of all null in the primitive datatype,
instead you should use Boolean class which can be null and suits your type of implementation.
Boolean notif = null;
if( notif == null ) {
System.out.println("notif is null");
} else {
if(notif){
System.out.println("notif is true");
} else {
System.out.println("notif is false");
}
}
Spring Expression Language (SpEL) in Spring Security to compare object use equals() or ==?
For example(method equals () is not called!):
class SecurityObject {
public boolean equals(Object obj) {
//...
}
}
#PreAuthorize(" #secObject == #otherSecObject ")
public void securityMethod(SecurityObject secObject, SecurityObject otherSecObject) {
//...
}
This is normal!? I need to use #PreAuthorize(" #secObject.equals(#otherSecObject) ") everywhere?
UPDATE
Why in first case Spring Security calling .equals(), and the second not?
//TestObject
public class TestObject {
private static final Logger log = LoggerFactory.getLogger(TestObject.class);
private Long id;
public TestObject(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.id);
return hash;
}
#Override
public boolean equals(Object obj) {
log.info("equals");
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TestObject other = (TestObject) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
}
//TestService
#PreAuthorize(" #one == #two ")
public String testEqualsInAnnotation(Long one, Long two) {
//...
}
#Override
#PreAuthorize(" #one == #two ")
public String testEqualsInAnnotation(TestObject one, TestObject two) {
//...
}
//Test
log.info("for Long");
Long one = new Long(500);
Long two = new Long(500);
log.info("one == two: {}", (one==two)? true : false); // print false
log.info("one equals two: {}", (one.equals(two))? true : false); // print true
testService.testEqualsInAnnotation(one, two); //OK
log.info("for TestObject");
TestObject oneObj = new TestObject(new Long(500));
TestObject twoObj = new TestObject(new Long(500));
log.info("oneObj == twoObj: {}", (oneObj==twoObj)? true : false); // print false
log.info("oneObj equals twoObj: {}", (oneObj.equals(twoObj))? true : false); // print true
testService.testEqualsInAnnotation(oneObj, twoObj); // AccessDeniedException: Access is denied
UPDATE 2
equals() never invoked at all
package org.springframework.expression.spel.ast;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.support.BooleanTypedValue;
/**
* Implements equality operator.
*
* #author Andy Clement
* #since 3.0
*/
public class OpEQ extends Operator {
public OpEQ(int pos, SpelNodeImpl... operands) {
super("==", pos, operands);
}
#Override
public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException {
Object left = getLeftOperand().getValueInternal(state).getValue();
Object right = getRightOperand().getValueInternal(state).getValue();
if (left instanceof Number && right instanceof Number) {
Number op1 = (Number) left;
Number op2 = (Number) right;
if (op1 instanceof Double || op2 instanceof Double) {
return BooleanTypedValue.forValue(op1.doubleValue() == op2.doubleValue());
} else if (op1 instanceof Long || op2 instanceof Long) {
return BooleanTypedValue.forValue(op1.longValue() == op2.longValue());
} else {
return BooleanTypedValue.forValue(op1.intValue() == op2.intValue());
}
}
if (left!=null && (left instanceof Comparable)) {
return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) == 0);
} else {
return BooleanTypedValue.forValue(left==right);
}
}
}
As per spEL documentation, You need to create ExpressionParser instance, create an Expression instance and get the value like below
String name = "Nikola Tesla";
Expression exp = parser.parseExpression("name == 'Nikola Tesla'");
boolean result = exp.getValue(Boolean.class);
result evaluates to 'true'. That says when we need to compare any two objects, then we need to override the equals() method and pass the two objects in to parser#parseExpression("obj1 == obj2") and then call the exp#getValue(Boolean.class) to evaluate. In the similar way, the Expression instance can also have expression string containing Obj1.equals(Obj2) for checking the equality. so, both the ways of checking equality are possible with spEL.
You may have discovered this already, since it is in the OpEq code in 'Update 2' of the original post, but...
The comparison operators lt < gt > le <= ge >= eq == ne != are based on java's Comparable interface.
So, if you've got a custom type that you want to be able to compare using == or != in SpEL expressions, then you could write it to implement Comparable.
Of course, then you'll have to figure out some sane rule to decide which object is before the other when they're not equivalent.
That said, I can't find anything in Spring's current documentation indicating this.
rdm, I think you have to use permission evaluator to evaluate the expressions. I don't think you have really injected/passed values for the objects in the following expression.
#Override
#PreAuthorize(" #one == #two ")
public String testEqualsInAnnotation(TestObject one, TestObject two) {
//...
I tried to do the same thing, but I failed to pass values, hence couldn't able to evaluate the expressions. My suggestion is to implement your custom permission evaluator for the above expression, and inject/pass values from the evaluator. To generalize my idea, my suspect is the objects are null, that is why you couldn't able to evaluate it. Please let us know if you can really pass values of the objects inside here : #PreAuthorize(" #one == #two ")
Added:
I am using permission evaluator to evaluate expressions under #PreAuthorize(...) annotation. Because I couldn't able to pass values to the parameters as I explained above. If it is possible to pass/inject values, it will be good to reduce complexity that can come from using permission evaluator.
rdm or others, can you point me how to pass the values for the parameters under #PreAuthorize(...) if possible?
Sorry for asking another question on rdm's post, and thank you in advance for your help!.
so i have this method:
class A(){
private Boolean Flag;
public java.lang.Boolean getFlag()
{
return this.Flag;
}
public java.lang.Boolean setFlag(Boolean Flag)
{
this.Flag = Flag ;
}
}
classB(){
boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag(navalFlag?"Y":"N";
}
database returns null and Flag is set to null.
What is a foolproof way where I can 100% avoid NPEs? I know Boolean to boolean casting is not a guarantee as seen from here
Update:
stepping through the code, the NPE is thrown in fancyObj.getFlag()...which doesn't make sense to me. i would expect the NPE thrown in .setNavalFlag....
What is a foolproof way where I can 100% avoid NPEs?
One foolproof way is to explicitly check for null and to not attempt to unbox the Boolean unless you know it's not null.
To take your current code as an example:
boolean navalFlag = fancyObj.getFlag()
This tries to unbox the Boolean. If it's null, you get an NPE.
The following modification will not have this problem:
Boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag((navalFlag != null && navalFlag) ? "Y" : "N");
Boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag((navalflag != null && navalFlag) ? "Y" : "N");
Edit of the Edit, as I had understood wrongly your comment :
See my answer to the comment: boolean navalFlag = fancyObj.getFlag() is automatically translated to boolean navalFlag = fancyObj.getFlag().booleanValue()
Change your method
public java.lang.Boolean getFlag()
{
return this.Flag;
}
to something like
public java.lang.Boolean getFlag()
{
(Flag==null) ? Boolean.FALSE : Flag;
}
Use boolean primitive type, not wrapper in your value object.
If you retrieve the value from database yourself, you will have to be careful, you will have to understand how to interpret null, normally it is false.
As the title suggests, I'm looking for a compare-and-swap implementation, but with greater-than comparison:
if(newValue > oldValue) {
oldValue = newValue;
}
where oldValue is some global shared state and newValue is private to each thread, without doing this:
synchronized(locker) {
if(newValue > oldValue) {
oldValue = newValue;
}
}
because I want a non-blocking solution. From studying source codes of other non-blocking operations, I've come up with this (assuming the values are integers):
AtomicInteger oldValue; // shared global variable
...
public boolean GreaterThanCAS(int newValue) {
while(true) {
int local = oldValue;
if(local == oldValue) {
if(newValue > local) {
if(oldValue.compareAndSet(local, newValue) {
return true; // swap successful
} // else keep looping
} else {
return false; // swap failed
}
} // else keep looping
}
}
when // else keep looping happens, it means that another thread has changed the oldValue in the meantime and so I need to loop and try again.
Is this implementation correct (thread-safe)?
Since Java 8 this can be simplified with use of updateAndGet:
public boolean greaterThanCAS(int newValue) {
return oldValue.updateAndGet(x -> x < newValue ? newValue : x) == newValue;
}
Note that this would return true also in case when old and new values are equal.
Give a try to #Adam's answer if this is not desired behaviour.
I see no problems with your implementation, provided that no thread ever decreases the value of the AtomicInteger. If they do, your code is open to race conditions.
Note that the code can be simplified as follows:
public boolean GreaterThanCAS(int newValue) {
while(true) {
int local = oldValue.get();
if(newValue <= local) {
return false; // swap failed
}
if(oldValue.compareAndSet(local, newValue)) {
return true; // swap successful
}
// keep trying
}
}
I would re write it to look more like:
while(true) {
int local = oldValue.get();
if(newValue > local){
if(oldValue.compareAndSwap(local, newValue) {
return true; // swap successful
} // else keep looping
}else
return false;
}
The equivalence check before the greater than check is redundant.
Otherwise it should work fine.
#Vadzim, I would have commented on your post, but stackoverflow says I don't have enough points to post comments. Your answer is almost correct, but your function will always return false because getAndUpdate always returns the previous value, or 'x' in your case. I think all you would need to do is replace your last '==' with '<', e.g.:
// return true if the assignment was made, false otherwise
public boolean greaterThanCAS(int newValue) {
return oldValue.getAndUpdate(x -> x < newValue ? newValue : x) < newValue;
}
Is there a better way to negate a boolean in Java than a simple if-else?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
theBoolean = !theBoolean;
theBoolean ^= true;
Fewer keystrokes if your variable is longer than four letters
Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.
There are several
The "obvious" way (for most people)
theBoolean = !theBoolean;
The "shortest" way (most of the time)
theBoolean ^= true;
The "most visual" way (most uncertainly)
theBoolean = theBoolean ? false : true;
Extra: Toggle and use in a method call
theMethod( theBoolean ^= true );
Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.
This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)
Boolean.valueOf(aBool).equals(false)
or alternatively:
Boolean.FALSE.equals(aBool)
or
Boolean.FALSE::equals
If you use Boolean NULL values and consider them false, try this:
static public boolean toggle(Boolean aBoolean) {
if (aBoolean == null) return true;
else return !aBoolean;
}
If you are not handing Boolean NULL values, try this:
static public boolean toggle(boolean aBoolean) {
return !aBoolean;
}
These are the cleanest because they show the intent in the method signature, are easier to read compared to the ! operator, and can be easily debugged.
Usage
boolean bTrue = true
boolean bFalse = false
boolean bNull = null
toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true
Of course, if you use Groovy or a language that allows extension methods, you can register an extension and simply do:
Boolean b = false
b = b.toggle() // == true
The class BooleanUtils supportes the negation of a boolean. You find this class in commons-lang:commons-lang
BooleanUtils.negate(theBoolean)
Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;
Boolean inverse = original == null ? null : !original;
If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.
public class Util {
public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }
}
then just create a Util object
Util u = new Util();
and have something for the return System.out.println( u.flip(bool) );
If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)
Before:
boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
After:
boolean result = isresult();
result ^= true;