Pages

Wednesday, February 3, 2010

Java Tips

Share it Please
1. We have a options for instance initializers which look like this ,
@SuppressWarnings("serial")
ArrayList simpleList=new ArrayList() {{
add("jagadesh");
add("proKarma");
add("software");
}};
You can initialize the arraylist while constructing it .
2. There is a faclilty in instanceOf keyword.this was implemented in such a way that there is no need to check for null ,
Consider
If(someObject != null && someObject instanceOf String){ }
Is equals to
If(someObject instanceOf String) { } which checks for the null also.
3.It is possible in java to call private methods and access private fields by using reflection , this snippet explains the syntax .
public class Foo {

private String myName;
public String yourName;

public String getMyName() {
return myName;
}

private void setMyName(String myName) {
this.myName = myName;
}
public String getYourName() {
return yourName;
}
public void setYourName(String yourName) {
this.yourName = yourName;
}

@Override
public String toString() {
return myName;
}

}

And main in class ,
public class SampleClass {

public static void main(String[] args)throws SecurityException,NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {

Foo obtainedFoo=new Foo();
Method obtainedMethod=Foo.class.getDeclaredMethod("setMyName", String.class);
obtainedMethod.setAccessible(true);
obtainedMethod.invoke(obtainedFoo, "jagadesh");

System.out.println(obtainedFoo.getMyName());
}
}

4.Shutdown Hooks :
We can make a thread to register that will be created immediately but called only when the jvm is ends , it look as
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run() {
System.out.println("Jvm Exit");
}
});

Will be back with some more tips , Happy Coding

No comments :

Post a Comment