当使用 JAXB(从 XSD)生成的 ObjectFactory 类时,我想将其存储在字段甚至常量中,因此我不必在私有方法之间传递它。据我所知,ObjectFactory 没有任何状态,至少对于我没有使用过的模式来说是这样。
是否存在这样的情况,例如,当使用特定的 XSD 构造或 JAXB 属性时,ObjectFactory 不是无状态的?
如果有,使用静态常量存储 ObjectFactory 是否安全,或者是否存在线程安全问题?
我正在尝试创建一些Java类,它们应该使用float或double数字(出于模拟目的,我需要支持两者).这些类需要做一些基本的算术,还需要使用三角函数(sin,cos,atan2).
我试着做一个通用的方法.由于Java不允许泛型中的原始类型并且MyClass<T extends Number>确实允许Double和Float,但是基本算法不可能,我在Double和Float周围构建了一个包装类.但是,只要我需要在其中一个泛型类中实例化一个值,这种方法就会失败.
是否有任何干净的方式来支持float和double,而不重复每种类型的所有代码?
我正在尝试使用自定义类型将持续时间对象(从ruby-duration gem)转储到yaml,因此它们在表单中表示hh:mm:ss.我试图修改这个问题的答案,但是在使用YAML.load解析yaml时,会返回Fixnum而不是Duration.有趣的是,Fixnum是持续时间中的总秒数,因此解析似乎有效,但在此之后转换为Fixnum.
我的代码到目前为止:
class Duration
def to_yaml_type
"!example.com,2012-06-28/duration"
end
def to_yaml(opts = {})
YAML.quick_emit( nil, opts ) { |out|
out.scalar( to_yaml_type, to_string_representation, :plain )
}
end
def to_string_representation
format("%h:%m:%s")
end
def Duration.from_string_representation(string_representation)
split = string_representation.split(":")
Duration.new(:hours => split[0], :minutes => split[1], :seconds => split[2])
end
end
YAML::add_domain_type("example.com,2012-06-28", "duration") do |type, val|
Duration.from_string_representation(val)
end
Run Code Online (Sandbox Code Playgroud)
澄清一下,我得到了什么结果:
irb> Duration.new(27500).to_yaml
=> "--- !example.com,2012-06-28/duration 7:38:20\n...\n"
irb> YAML.load(Duration.new(27500).to_yaml)
=> 27500
# should be <Duration:0xxxxxxx @seconds=20, @total=27500, @weeks=0, @days=0, @hours=7, @minutes=38>
Run Code Online (Sandbox Code Playgroud)