简书链接:java单例转kotlin的表现
文章字数:55,阅读全文大约需要1分钟
java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class TestStatic { private static final String TAG = "TestStatic"; private static TestStatic instance; private static TestStatic staticField; private TestStatic notStaticField;
public static TestStatic getInstance() {
if (instance == null) { synchronized (TestStatic.class) { if (instance == null) { return new TestStatic(); } } }
return instance; }
public TestStatic reflect() {
try { Class<?> aClass = Class.forName(staticField.getClass().getName()); Field[] declaredFields = aClass.getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); System.out.println("FIELD:" + field.getName() + "," + TAG); } } catch (ClassNotFoundException e) { e.printStackTrace(); } return staticField; }
public static void main() { TestStatic obj = TestStatic.getInstance(); TestStatic notStaticField = obj.notStaticField; System.out.println("note" + notStaticField); } }
|
kotlin代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| internal class TestStatic { private val notStaticField: TestStatic? = null
fun reflect(): TestStatic? {
try { val aClass = Class.forName(staticField!!.javaClass.name) val declaredFields = aClass.declaredFields for (field in declaredFields) { field.isAccessible = true println("FIELD:" + field.name + "," + TAG) } } catch (e: ClassNotFoundException) { e.printStackTrace() }
return staticField }
companion object { private val TAG = "TestStatic" private val instance: TestStatic? = null private val staticField: TestStatic? = null
fun getInstanceXXX(): TestStatic? {
if (instance == null) { synchronized(TestStatic::class.java) { if (instance == null) { return TestStatic() } } }
return instance }
fun main() { val obj = TestStatic.getInstanceXXX() val notStaticField = obj!!.notStaticField println("note" + notStaticField!!) } } }
//因为getInstance()刚好和默认获取的事例冲突,所以方法名改了下才解决一键转换错误
|
在其他kotlin文件中的调用
1 2
| val obj = TestStatic.getInstanceXXX() println("hello obj${obj}")
|
完美