Skip to content

Commit

Permalink
小傅哥,Java 面经手册 • 拿大厂Offer,第 31 章 源码
Browse files Browse the repository at this point in the history
  • Loading branch information
fuzhengwei committed May 2, 2021
1 parent e9256e6 commit 5cbf5c5
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
26 changes: 26 additions & 0 deletions interview-31/src/test/java/org/itstack/interview/test/ABTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.itstack.interview.test;

/**
* 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获!
* 公众号:bugstack虫洞栈
* Create by 小傅哥(fustack)
*/
public class ABTest {

public static void main(String[] args) {
new ClazzA();
}

}

class ClazzA {

private ClazzB b = new ClazzB();

}

class ClazzB {

private ClazzA a = new ClazzA();

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package org.itstack.interview.test;

import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -10,10 +13,6 @@ public class CircleTest {
private final static Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

public static void main(String[] args) throws Exception {
Class[] classes = {A.class, B.class};
for (Class clazz : classes) {
getBean(clazz);
}
System.out.println(getBean(B.class).getA());
System.out.println(getBean(A.class).getB());
}
Expand All @@ -23,23 +22,25 @@ private static <T> T getBean(Class<T> beanClass) throws Exception {
if (singletonObjects.containsKey(beanName)) {
return (T) singletonObjects.get(beanName);
}

Object obj = beanClass.getDeclaredConstructor().newInstance();
// 实例化对象入缓存
Object obj = beanClass.newInstance();
singletonObjects.put(beanName, obj);

// 属性填充补全对象
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Class<?> fieldClass = field.getType();
String fieldBeanName = fieldClass.getSimpleName().toLowerCase();
field.set(obj, singletonObjects.containsKey(fieldBeanName) ? singletonObjects.get(fieldBeanName) : getBean(fieldClass));
field.setAccessible(false);
}
return (T) obj;
}

}

class A {

private B b;

public B getB() {
Expand Down

0 comments on commit 5cbf5c5

Please sign in to comment.