Skip to content

Instantly share code, notes, and snippets.

public static Method findMethod(Class<?> clazz, String name, Class<?>[] paramTypes) {
Class<?> searchType = clazz;
while (searchType != null) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (name.equals(method.getName()) &&
(paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
return method;
}
}
interface I {
public void f();
}
class A implements I {
public void f() { System.out.println("A: doing f()"); }
}
class B implements I {
public void f() { System.out.println("B: doing f()"); }
// changing the implementing object in run-time (normally done in compile time)
class C implements I {
private I i;
// forwarding
public C(I i){ this.i = i; }
public void f() { i.f(); }
}
public class Main {
public static void main(String[] arguments) {
C c = new C(new A());
c.f(); // output: A: doing f()
c = new C(new B());
c.f(); // output: B: doing f()
}
}
Integer one = Integer.valueOf(1);
Integer[] ones = new Integer[]{one,one,one,one};
Integer[] anotherOnes = ones;
Number[] numberOnes = ones;
//Integer[] illegalOnes=new Integer[]{"1","1","1","1"};
String str ="one";
String[] strs =new String[]{str};
String[] anotherStrs =strs;
public static Method findMethod(Class<?> clazz, String name, @Nullable Class<?>... paramTypes) {
Class<?> searchType = clazz;
while (searchType != null) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (name.equals(method.getName()) &&
(paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
return method;
}
}
class Driver {
}
class Vehicle {
private Driver driver;
public Vehicle withDriver(Driver driver)
this.driver = driver;
return this;
}
class SomeService {
public int calcNumberOfWheels(Car[] cars){
int length = (cars==null)?0:cars.
if(length==0){
return 0;
}
long sum = 0L;
int cur = 0;
Car car = null;
Car[] cars={new Car(), new Car(), new SportCar()};
Object[] arr=cars; //arrays are covariant, it is legal assignment
arr[0]=new Motorcycle(); //as far as compiler concerns, it is legal, but this will crash at runtime with ArrayStoreException
Car[] cars={new Car(), new Car(), new SportCar()};
Object[] arr=cars; //arrays are covariant, it is legal assignment
arr[0]=new Motorcycle(); //as far as compiler concernt, it is legal, we're assiming no-runtime check
System.out.println(cars[0] instanceof Car); //false, WTF?
cars[0].someCarMethod(); //crash at runtime