我的应用程序包含几个JAR文件.我想迭代所有JAR文件并找到子类化特定类的所有类,以便我可以使它们的静态初始化器运行.
我查看了java.lang.ClassLoader的Javadocs,但找不到任何执行此操作的方法.
我正在尝试实现"Product Trader"模式(http://www.ubilab.com/publications/print_versions/pdf/plop-96-producttrader.pdf),在抽象超类中使用"自注册"类.超类将有一个HashMap,它映射子类提供的服务和处理该服务的java.lang.Class文件.
问题是类在加载之前不会运行它的静态初始值设定项.如果我可以迭代所有子类,我可以强制每个子加载并运行它的初始化器.
谢谢,拉尔夫
我需要处理代表人的大量记录(数百万).我想根据出生年份创建一个分区,然后分别处理每个组.我正在尝试创建一个功能性解决方案(没有/最小可变数据),因此它将是线程安全的并且可以并行化.
在我的第一次尝试中,我创建了一个尾递归函数,该函数构建了一个Map[Int, IndexedSeq]
将每个出生年份映射到一系列人员记录的函数.我需要一个索引序列,因为我将对每个组中的人进行随机访问.这是我的代码:
@tailrec
def loop(people: Seq[Person],
map: Map[Int, IndexedSeq[Person]] = Map()): Map[Int, IndexedSeq[Person]] = {
if (people.isEmpty) map
else {
val person = people.head
val yearOfBirth = person.yearOfBirth
val seq = map.getOrElse(yearOfBirth, IndexedSeq())
loop(people.tail, map + (yearOfBirth -> (seq :+ person)))
}
}
Run Code Online (Sandbox Code Playgroud)
这有效,但效率不高.通过允许少量非常局部化的可变性,我可以做得更好.如果所有可变变量都在堆栈上,只要输出Map
是不可变的,代码仍然是线程安全的.
我想通过内部构建一个mutable来实现它Map[Int, List[Person]]
,然后有效地将它转换为一个不可变Map[Int, IndexedSeq[Person]]
的返回值.
我怎么能转换可变Map
的List
项目不可变Map[Int, IndexedSeq[Person]]
的最有效的方式可能吗?请注意,每个出生年份组的人员没有特别的顺序.
我试图将以下Scala 2.9隐式转换方法转换为2.10隐式类:
import java.sql.ResultSet
/**
* Implicitly convert a ResultSet to a Stream[ResultSet]. The Stream can then be
* traversed using the usual map, filter, etc.
*
* @param row the Result to convert
* @return a Stream wrapped around the ResultSet
*/
implicit def stream(row: ResultSet): Stream[ResultSet] = {
if (row.next) Stream.cons(row, stream(row))
else {
row.close()
Stream.empty
}
}
Run Code Online (Sandbox Code Playgroud)
我的第一次尝试没有编译:
implicit class ResultSetStream(row: ResultSet) {
def stream: Stream[ResultSet] = {
if (row.next) Stream.cons(row, stream(row))
else {
row.close()
Stream.empty
} …
Run Code Online (Sandbox Code Playgroud) 我有一个case class
包含命令行配置信息的Scala :
case class Config(emailAddress: Option[String],
firstName: Option[String]
lastName: Option[String]
password: Option[String])
Run Code Online (Sandbox Code Playgroud)
我正在编写一个验证函数来检查每个值是否为Some
:
def validateConfig(config: Config): Try[Config] = {
if (config.emailAddress.isEmpty) {
Failure(new IllegalArgumentException("Email Address")
} else if (config.firstName.isEmpty) {
Failure(new IllegalArgumentException("First Name")
} else if (config.lastName.isEmpty) {
Failure(new IllegalArgumentException("Last Name")
} else if (config.password.isEmpty) {
Failure(new IllegalArgumentException("Password")
} else {
Success(config)
}
}
Run Code Online (Sandbox Code Playgroud)
但如果我理解来自Haskell的monad,似乎我应该能够将验证链接在一起(伪语法):
def validateConfig(config: Config): Try[Config] = {
config.emailAddress.map(Success(config)).
getOrElse(Failure(new IllegalArgumentException("Email Address")) >>
config.firstName.map(Success(config)).
getOrElse(Failure(new IllegalArgumentException("First Name")) >>
config.lastName.map(Success(config)).
getOrElse(Failure(new IllegalArgumentException("Last Name")) …
Run Code Online (Sandbox Code Playgroud) 以下编译没有警告或错误.
factors n = [x | x<-[1..n], n `mod` x == 0]
perfects n = [x | x <- [1..n], x == sum (factors (init x))]
main = putStrLn "hello"
Run Code Online (Sandbox Code Playgroud)
即使我犯了错误.
perfects n = [x | x <- [1..n], x == sum (factors (init x))] -- incorrect
perfects n = [x | x <- [1..n], x == sum (init (factors x))] -- should have been
Run Code Online (Sandbox Code Playgroud)
静态类型检查在哪里进行救援?
我认为应该抓住错误的原因是:
factor
显然期望一个Integral
因为它的参数使用mod
,而init
返回aList
x
从绘制List …
以下函数是Yesod REST服务器的一部分,通过电子邮件地址在MongoDB数据库中搜索现有用户,并返回Maybe User
:
{-# LANGUAGE DeriveGeneric #-}
module Model.User where
import Database.MongoDB (Action, findOne, select, (=:))
import qualified Database.MongoDB as M
import GHC.Generics (Generic)
import Import
data User = User
{ userEmail :: Text
, userFirstName :: Text
, userLastName :: Text
} deriving (Generic, Show)
collection :: Text
collection = "users"
instance FromJSON User
instance ToJSON User
findForEmail :: Text -> Action IO (Maybe User)
findForEmail email = do
maybeDocument <- findOne (select [ "email" =: email …
Run Code Online (Sandbox Code Playgroud) 在本机应用程序中,我具有以下样式
const styles = StyleSheet.create({
text: {
textAlign: "center"
},
})
Run Code Online (Sandbox Code Playgroud)
在中使用<Text style={styles.text} />
,但tsc
编译器给出以下错误:
Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.
Run Code Online (Sandbox Code Playgroud)
TextStyle
in 的定义@types/react-native
包括:
export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
// ...
textAlign?: "auto" | "left" | "right" | "center"
// ...
}
Run Code Online (Sandbox Code Playgroud)
为什么编译器抱怨不兼容?似乎是在推断类型textAlign
过于笼统,string
而不是检查实际值("center"
)。
我知道我可以使用a as TextStyle
来避免该问题,但是我想知道为什么会发生这种情况以及是否应该向编译器提交故障单。
在下面的代码示例中,结果不是我期望的:
package main
import "fmt"
func main() {
src := map[int]int{1: 1, 2: 2, 3: 3}
fmt.Println("src ", src)
dst := make([]*int, 0, len(src))
for k, _ := range src {
dst = append(dst, &k)
}
for _, a := range dst {
fmt.Print(*a, " ")
}
fmt.Println()
}
Run Code Online (Sandbox Code Playgroud)
结果:
src map[1:1 2:2 3:3]
3 3 3
Run Code Online (Sandbox Code Playgroud)
前往游乐场:https : //play.golang.org/p/BSDsd3nojz
但我知道发生了什么事。的不变地址k
被添加到dst
,因此当我循环遍历时dst
,每个位置都有相同的值:3
。
k
在循环中,永不改变的地址,因此第二个循环继续引用该位置,其中包含其最后一个值3
。
如何获取k
要复制的当前值的地址?我需要这样的东西吗:
for k, _ …
Run Code Online (Sandbox Code Playgroud) 我有一个Scala Option[T]
.如果值是Some(x)
我想用一个不返回值(Unit
)的进程处理它,但如果是None
,我想打印一个错误.
我可以使用下面的代码要做到这一点,但我明白,更习惯的方法是治疗Option[T]
的顺序和使用map
,foreach
等我该怎么办呢?
opt match {
case Some(x) => // process x with no return value, e.g. write x to a file
case None => // print error message
}
Run Code Online (Sandbox Code Playgroud) 我正在阅读"真实世界Haskell"(好书),我对编译器如何选择重载函数感到困惑.
如果我有一个类型类
type JSONError = String
class JSON a where
toJValue :: a -> JValue
fromJValue :: JValue -> Either JSONError a
Run Code Online (Sandbox Code Playgroud)
和这样的两个实例
instance JSON Bool where
toJValue = JBool
fromJValue (JBool b) = Right b
fromJValue _ = Left "not a JSON boolean"
Run Code Online (Sandbox Code Playgroud)
和
instance JSON String where
toJValue = JString
fromJValue (JString s) = Right s
fromJValue _ = Left "not a JSON string"
Run Code Online (Sandbox Code Playgroud)
编译器如何在两个"fromJValue"函数之间进行选择,例如,给出一个Integer?
scala ×4
haskell ×3
monads ×2
classloader ×1
composition ×1
either ×1
for-loop ×1
go ×1
immutability ×1
java ×1
map ×1
overloading ×1
parsing ×1
reference ×1
scala-option ×1
typechecking ×1
typeclass ×1
typescript ×1
yesod ×1