I am unable to create an object using singleton design pattern, here is what I did:
class Test {
public static Test objTest = null;
public static int count = 0;
public static Test CreateObject() {
if (objTest != null)
objTest = new Test();
return objTest;
}
private Test() {
Test.count++;
}
}
Have I created zeroton pattern ?
Check your if condition inside createObject method once. it should be if(objTest == null) .
Besides the fact, that your count would always be either '0' or '1' (ignoring potential multi-threading issues) - why do you have that parameter?
You are checking for objTest != null instead of objTest == null.
That's why you are always returning null and never create a new instance.
The objTest variable should also be private, you'll not want to reference to a null instance. Access to the instance should only be possible through your CreateObject() method.
Related
I want to annotated 2 different methods and related them together in order to match the global variable and method which uses it
#FirstAnn(funcName = "foo")
def foo = {
val value = boo()
val checkValue = value > 2
return checkValue
}
#SecondAnn(funcName = "foo", paramName = "value")
def boo : Double = {
return B.getValue
}
#Pointcut("execution(* *(..)) && #annotation(firstAnn) && if()")
public static boolean execute(FirstAnn firstAnn){
return true;
}
#Pointcut("execution(* *(..)) && #annotation(secAnn) && if()")
public static boolean execute2(SecondAnn secAnn){
return true;
}
#Before("execute(firstAnn) && execute2(secAnn)")
public void before(FirstAnn firstAnn, SecondAnn secAnn, JoinPoint.StaticPart jps,JoinPoint jp){
if (firstAnn.funcName == secAnn.funcName){
print("value X is used in funcname Y" ) //here I will retrieve the value from signature like: value 3 is used in function foo
}
}
But the code doesn't get to this place...Any suggestion to make it work please?
thanks
Your usage of && implies you expect both methods to be executed at the same time. But of course they are not. Either the first or the second one is matched, they are two different joinpoints, thus combining the pointcuts with && will never make your advice method fire. You need to use || instead to match either one.
Looking at your source code, what you probably want is to trigger the advice when boo is called from within foo and possibly also the other way around. You are also trying to bleed context from the calling method into the called method. This is called a wormhole pattern, see also my answers here:
https://stackoverflow.com/a/12130175/1082681
https://stackoverflow.com/a/50577287/1082681
https://stackoverflow.com/a/25075051/1082681
So probably you want to use a pointcut like
execute2(secAnn) && cflow(execute(firstAnn))
for your example or the other way around if you have cases where the second method calls the first one:
cflow(execute2(secAnn)) && execute(firstAnn)
Is it possible to have a constructor decide, based on the argument, not to make a new instance? For example:
public class Foo{
public Foo(int n){
if(n<0){
//DO NOT make this
}
else{
//Go ahead and make this instance
}
}
}
I know it is not possible to do this:
public class Foo{
public Foo(int n){
if(n<0){
//DO NOT make this
this = null;
}
else{
//Go ahead and make this instance
}
}
}
Is there a way to do the same thing correctly?
A constructor has no control over what will be returned. However, you can use static factory methods for more flexibility:
public static Foo newInstance(int n) {
if (n < 0) {
return null;
} else {
return new Foo(n);
}
}
It's better to throw an exception than return null when an invalid number is supplied:
if (n < 0) {
throw new IllegalArgumentException("Expected non-negative number");
} ...
A constructor does not return an instance. The new operator (as part of the instance creation expression) creates the instance and the constructor initializes it. Once you've understood that, you realize you can't do what you are suggesting.
Your calling code should decide if it creates an instance or not, not the constructor.
You can not do what you are wanted to do. But if your requirement is to have instance creation based on some condition you can have a static method for that class and based on condition u decide whether to create a new instance or not.
I am really tired of doing all the if null checks, resp. I also want to have a more configurable scenario for this. Let me explain this by an example:
I have a getter() which may return null or '0' in both cases the resp. setter() should not be called passing the getter().
So the implementation is
if(getter() != null && !getter().equals('0')) setter(getter());
this however really anoys me, especially if getter() and setter() are really long method calls and I have to introduce helper variables for this.
I am thinking about a method with parameter
ifNotSet(getter(), setter(), new Object[null, '0']);
which does exactly the same thing. Where the parameters to ifNotSet are
getter - the method to check if it does not equal one of the conditions
setter - the method to call in the way setter(getter) if conditions does not apply
conditions - the conditions which must not apply on evaluation of getter() for the method to be executed
At first sight this does not seem to complicated, it however is! Is anyone aware of a solution to this problem or any kind of implementation?
Thanks!
Update
I've been working some more on the problem, after the feedback of you guys, and found out about the following
private boolean ns(Object[] condition, Object getter) {
boolean ret = false;
for (Object object : condition) {
if(getter) equals or == ??
}
return true;
}
Object[] cond = new Object[] { null, "0" };
Object a;
if (ns(cond, a = getter()))setter(a);
Well, this seemed to be at least a solution if you have a lot of allocations to do. However, if you take a look at the ns() method... the question on the incoming conditions is, whether to use == or equals to do the comparison!?
You can use this way
public boolean checkNotNullOrZero(String s)
{
return (s!=null) && !s.equals("0");
}
Basic use:
if(checkNotNullOrZero(getter()))
{
setter(getter());
}
You can't do what that as in Java methods are not first-class citizens. You could use reflection or anon classes but it would be way more work .
If null and zero are always equivalent for getter then could that be changed to return just one of the two?
If null and zero are always equivalent for setter then could that be changed to normalize the two?
Could you create a method isNullOrZero(x) then you can have
if (!isNullOrZero(getter())) {
setter(getter());
}
Ugly way of doing this literally in Java:
public interface Getter {
public Object get();
}
public interface Caller {
public void call();
}
public void callIfNotNull(Getter getter, Caller caller, Object[] nullObjects) {
Object value = getter.get();
for(Object nullObject : nullObjects) {
if(value==nullObject) {
return;
}
}
caller.call();
}
Usage:
callIfNotNull(new Getter() {
#Override
public Object get() {
return getterMethod();
}
}, new Caller() {
#Override
public void call() {
setter();
}
}, new Object[]{null, '0'});
}
You might need to implement sane way to check for null objects and give reasonable names.
Personnaly, I wouldn't go with this approach. I would try to implement Null Object pattern to resolve an issue.
I want to throw exception if all fields in object are null, but traditional way for checking on null looks not very smart. What can be another way to do this?
EDIT : This uses reflection (java.lang.reflect.Field)
You could create a method within this object to return its valid state :
public boolean isValid() {
boolean isValid = true;
for (int i = 0; isValid && i < this.getClass().getFields().length; ++i) {
if (this.getClass().getFields()[i].equals(null)) {
isValid = false;
}
}
return isValid;
}
This way, the method is going to validate each and every field of the class so you don't need to modifiy the code whenever you add a new field to it.
HOWEVER,
the primary key cannot be null, so you have NOT to validate this field, or any NOTNULL field for that matter.
if (!field.getName().equals("aPrimaryKey_OR_aNotNullField")) {
}
Try this:
if (a == null && b == null && c == null)
throw new AllFieldsAreNullException();
You could potentially use reflection to write a generic method to analyse fields of an object, but it doesn't seem the clearest way of performing validation. I would perhaps be explicit for clarity's sake.
public LeNo generate (PrintStream stream) {
prepareOperands(stream);
LeNo l = (LeNo)left;
LeNo r = (LeNo)right;
if (l instanceof NumNo && r instanceof NumNo) {
return new NumNo((Integer.getInteger(l.name()).intValue()*Integer.getInteger(r.name())));
}
if ((l instanceof NumNo && l.name().equals("0"))||(r instanceof NumNo && r.name().equals("0"))) {
return new NumNo(0); // cut of rest of code here....
Is there a way I can create a new NumNo method without having to create it when I return?
The thing is I still want to return NumNo, but without creating a new NumNo doing it.
It is just return new NumNo(0); that you don't want to create right? Because it is the same every time? If so, you can create a static instance of that object. For example,
private static final NewNo ZERO = new NewNo(0);
This is called the flyweight pattern, where you create commonly used instances once.
return NumNo.getClass();
To return a class instead of an instance.
Create an instance with java.lang.Class.newInstance()
for example:
klass = generate(stream);
object = klass.newInstance();