#10 effective java: item 1

This commit is contained in:
haerong22
2022-05-07 03:12:50 +09:00
parent c2a0211113
commit e16a8ee85e
5 changed files with 65 additions and 1 deletions

View File

@@ -0,0 +1,12 @@
package com.example.effectivejava.chapter01.item01;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
HelloService helloService = applicationContext.getBean(HelloService.class);
System.out.println(helloService.hello());
}
}

View File

@@ -0,0 +1,13 @@
package com.example.effectivejava.chapter01.item01;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public HelloService helloService() {
return new ChineseHelloService();
}
}

View File

@@ -0,0 +1,8 @@
package com.example.effectivejava.chapter01.item01;
public class ChineseHelloService implements HelloService {
@Override
public String hello() {
return "ni hao";
}
}

View File

@@ -1,15 +1,20 @@
package com.example.effectivejava.chapter01.item01;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import java.util.ServiceLoader;
public class HelloServiceFactory {
public static void main(String[] args) {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
ServiceLoader<HelloService> loader = ServiceLoader.load(HelloService.class);
Optional<HelloService> helloServiceOptional = loader.findFirst();
helloServiceOptional.ifPresent(h -> {
System.out.println(h.hello());
});
Class<?> aClass = Class.forName("com.example.effectivejava.chapter01.item01.ChineseHelloService");
HelloService helloService = (HelloService) aClass.getConstructor().newInstance();
System.out.println(helloService.hello());
}
}

View File

@@ -0,0 +1,26 @@
package com.example.effectivejava.chapter01.item01;
import java.util.ArrayList;
import java.util.Comparator;
public class ListQuiz {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(200);
numbers.add(30);
numbers.add(120);
numbers.add(2);
System.out.println("numbers = " + numbers);
Comparator<Integer> desc = (a, b) -> b - a;
numbers.sort(desc);
System.out.println("numbers = " + numbers);
numbers.sort(desc.reversed());
System.out.println("numbers = " + numbers);
}
}