buy lasix http://all-treatment.org/buy-levitra-vardenafil/ http://all-treatment.org/buy-viagra-sildenafil-citrat/ isotretinoin online buy cialis online
14 des. 2016

Trucs amb el Java

Author: Joaquim Perez Noguer | Filed under: Ciència i tecnologia

Mirant  What are some cool Java tricks? – Quora

He trobat algunes curiositats interessants amb el Java:

Double bracing Lists allows you to declare and initialize without Arrays.asList()
List<String> places = new ArrayList<String>() {
{ add(“x”); add(“y”); }
};

Joint-union in generic type params
public class Baz<T extends Foo & Bar> {}

Define, instantiate, and call all at once
new Object() {
void hi(String in) {
System.out.println(in);
}
}.hi(“weird”);

Detect deadlocks
public static class DeadLockDetector extends Thread {
@Override
public void run() {
while(true) {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
long[] ids = threadMXBean.findDeadlockedThreads();
if (ids != null) {
System.exit(127);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
}
}
}

Unsafe… (it’s like Super User mode for Java… dangerous but powerful). Understanding sun.misc.Unsafe
public void testObjectCreation() throws Exception {
ClassWithExpensiveConstructor instance =    (ClassWithExpensiveConstructor)
unsafe.allocateInstance(ClassWithExpensiveConstructor.class);
assertEquals(0, instance.getValue());
}

Però el que el millor sense cap dubte és el que es pot fer amb Reflection:

    import java.lang.reflect.Field;

public class MutableString {

public static void main(String[] args) throws Exception {
String someString = “IMMUTABLE”;
Field field = Class.forName(“java.lang.String”).getDeclaredField(“value”);
field.setAccessible(true);
char[] value = (char []) field.get(someString);
String anotherString = “NOTREALLY”;
for (int i=0; i<value.length; i++){
char c = anotherString.toCharArray()[i];
value[i]=c;
}

System.out.println(someString); // prints NOTREALLY
System.out.println(“IMMUTABLE”); // WTF !!! prints NOTREALLY
}
}

 

 



Leave a Reply