“new”中/后带有大括号的代码?
private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
我不明白星星内部发生了什么。这是将方法插入类的方法吗?
private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
I don't understand what's going on in the part that's within the stars. Is that a way to insert a method into a class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
initialValue() 方法只是构造一个持有非 null 值的 ThreadLocal 的方法。
编辑:哦,我明白这不是你问的问题。你所拥有的与你所做的一样:
除了你的版本不需要完全独立的类定义 - 因此它被称为“匿名类”。
The initialValue() method of ThreadLocal is just a way to construct a ThreadLocal holding a value other than null.
Edit: Oh, I see that's not what you're asking about. What you have there is the same as if you did:
Except your version doesn't require a completely separate class definition--hence it's called an "anonymous class".
这是一个匿名内部类 - 请参阅 http://download.oracle.com/javase/教程/uiswing/events/generalrules.html#innerClasses
This is an anonymous inner class - see http://download.oracle.com/javase/tutorial/uiswing/events/generalrules.html#innerClasses
在星星中,您有一个匿名内部类,这意味着:
它是实现的语法快捷方式接口或抽象类的行为,无需声明完整的标准 Java 类。您正在为固定上下文定义精确的行为。
接下来,对于ThreadLocal部分,基于ThreadLocal Javadoc中connectionHolder字段是由很多thead管理的。
如果你有 5 个线程访问 ConnectionHolder,你会发现 5 个 ThreadLocal 管理着该值的 5 个实例
Within the stars you have an anonymous inner class it means :
it's a syntax shortcut to implement a behavior for an interface or abstract class without declaring a full standard Java class. You are defining a precise behavior for a fixed context.
Next, for the ThreadLocal part,based on the ThreadLocal Javadoc the connectionHolder field is managed by many theads.
If you have 5 threads wich access to the connectionHolder you will found 5 ThreadLocal which managed the 5 instance of the value
这是一个匿名内部类,通常实现一些接口是回调或类似的东西,Swing 使用它作为侦听器。
在本例中,它在
ThreadLocal
的特定实例上实现initialValue()
方法。您可以通过这种方式重写对象的单个实例上的方法,因此,如果您只想某个特定实例以不同的方式运行,您可以重写该实例上任意数量的方法。
This is an Anonymous Inner Class that are usually implementing some interface that is a callback or something similar, Swing uses this for listeners.
In this case it is implementing the
initialValue()
method on that particular instance ofThreadLocal<Connection>
.You can override methods on single instances of Objects this way, so if you want just a particular instance to behave in a different way you can override as many methods on that instance you want.
这是一个匿名内部类。这是扩展基类的简短语法:
您可以使用接口执行相同的操作(最常见于实现回调时)。例如:
This is an anonymous inner class. It is a short syntax for extending a base class:
You could do the same thing with interfaces (most commonly seen when implementing callbacks). For example: