这两种实例化类的新对象的方法有什么区别,如下所示:
Test t1=new Test();
Test t2=new Test(){ };
Run Code Online (Sandbox Code Playgroud)
当我尝试下面的代码时,我可以看到两个对象都可以访问该方法foo()
,但是t2无法访问variable x
(variable x
无法解析):
public class Test
{
int x=0;
public void foo(){ }
public static void main (String args[])
{
Test t1=new Test();
Test t2=new Test(){ };
t1.x=10;
t2.x=20;
t1.foo();
t2.foo();
System.out.println(t1.x+" "t2.x);
}
}
Run Code Online (Sandbox Code Playgroud) private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
Run Code Online (Sandbox Code Playgroud)
我不明白星星内部发生了什么.这是一种将方法插入类的方法吗?
我如何{}
在Java中引用。它是新对象,类还是数据类型还是其他?
我正在通过json中的一些代码进行对象转换。它使用com.fasterxml.jackson.core.type.TypeReference
。我想了解是什么{}
。因为方法总是接受对象。当我这样做时new XXX()
,对象的创建就完成了。那么,额外需要什么{}
呢?
try {
return objectMapper.readValue(dbData, new TypeReference<List<MyClass>>() {});
} catch (IOException e) {
LOGGER.error("Exception while de-serializing", e);
return Collections.emptyList();
}
Run Code Online (Sandbox Code Playgroud)