java代码
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代码
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文件中的调用
val obj = TestStatic.getInstanceXXX()
println("hello obj${obj}")
完美
标签:java,val,kotlin,private,instance,TestStatic,单例,null,notStaticField From: https://blog.51cto.com/u_15458814/5883580