前几天我查看了一些代码,我遇到了:
static {
...
}
Run Code Online (Sandbox Code Playgroud)
来自C++,我不知道为什么会这样.它不是一个错误,因为代码编译得很好.什么是"静态"代码块?
在Java中,有什么区别:
private final static int NUMBER = 10;
Run Code Online (Sandbox Code Playgroud)
和
private final int NUMBER = 10;
Run Code Online (Sandbox Code Playgroud)
两者都是private和final,不同之处在于static属性.
什么更好?为什么?
说这static意味着所有对象的值的volatile一个副本并且意味着所有线程的值的一个副本是否正确?
无论如何,static变量值也将成为所有线程的一个值,那么我们为什么要这样做volatile呢?
非常常见的初学者错误是当您尝试"静态"使用类属性而不创建该类的实例时.它会留下您提到的错误消息:
您可以将非静态方法设为静态,也可以使该类的实例使用其属性.
为什么?我不是要求解决方案.我很高兴知道它背后的原因是什么.核心原因!
private java.util.List<String> someMethod(){
/* Some Code */
return someList;
}
public static void main(String[] strArgs){
// The following statement causes the error. You know why..
java.util.List<String> someList = someMethod();
}
Run Code Online (Sandbox Code Playgroud) 据我所知,"静态初始化块"用于设置静态字段的值,如果不能在一行中完成的话.
但我不明白为什么我们需要一个特殊的块.例如,我们将一个字段声明为静态(没有值赋值).然后编写几行代码,生成并为上面声明的静态字段赋值.
为什么我们需要在一个特殊的块这样的行这样的:static {...}?
java static initialization static-block initialization-block
我在这里读了几个关于静态方法的线程,我想我明白了误用/过度使用静态方法会导致的问题.但我并没有真正了解为什么很难模拟静态方法.
我知道其他嘲笑框架,如PowerMock,可以做到这一点,但为什么不能Mockito?
我读过这篇文章,但作者似乎在虔诚地反对这个词static,也许这是我理解不足的原因.
一个简单的解释/链接将是伟大的.
public class EnumRouteConstraint<T> : IRouteConstraint
where T : struct
{
private static readonly Lazy<HashSet<string>> _enumNames; // <--
static EnumRouteConstraint()
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException(
Resources.Error.EnumRouteConstraint.FormatWith(typeof(T).FullName));
}
string[] names = Enum.GetNames(typeof(T));
_enumNames = new Lazy<HashSet<string>>(() => new HashSet<string>
(
names.Select(name => name), StringComparer.InvariantCultureIgnoreCase
));
}
public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
bool match = _enumNames.Value.Contains(values[parameterName].ToString());
return match;
}
}
Run Code Online (Sandbox Code Playgroud)
这是错的吗?我会假设这实际上有一个static readonly字段用于EnumRouteConstraint<T>我碰巧实例化的每一个.
如何在C++中创建静态类?我应该可以这样做:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
Run Code Online (Sandbox Code Playgroud)
假设我创建了这个BitParser类.将在哪些BitParser类定义是什么样子?
我刚刚在代码库中找到了一个静态嵌套接口.
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
Run Code Online (Sandbox Code Playgroud)
我以前从未见过这个.最初的开发者是遥不可及的.因此我不得不问:
静态接口背后的语义是什么?如果我删除了会有什么变化static?为什么有人会这样做?
如何从该类中的静态方法获取类的名称.例如
public class MyClass {
public static String getClassName() {
String name = ????; // what goes here so the string "MyClass" is returned
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
为了把它放在上下文中,我实际上想要在异常中将类名作为消息的一部分返回.