Tomcat 系统架构与设计模式
Category Archives: JAVA
Java 8 简明教程
目 录
- 允许在接口中有默认方法实现
- Lambda表达式
- 函数式接口
- 方法和构造函数引用
- Lambda的范围
- 内置函数式接口
- Streams
- Parallel Streams
- Map
- 时间日期API
- Annotations
- 总结
“Java并没有没落,人们很快就会发现这一点”
欢迎阅读我编写的Java 8介绍。本教程将带领你一步一步地认识这门语言的新特性。通过简单明了的代码示例,你将会学习到如何使用默认接口方法,Lambda表达式,方法引用和重复注解。看完这篇教程后,你还将对最新推出的API有一定的了解,例如:流控制,函数式接口,map扩展和新的时间日期API等等。
允许在接口中有默认方法实现
Java 8 允许我们使用default关键字,为接口声明添加非抽象的方法实现。这个特性又被称为扩展方法。下面是我们的第一个例子:
1
2
3
4
5
6
7
|
interface Formula { double calculate( int a); default double sqrt( int a) { return Math.sqrt(a); } } |
在接口Formula中,除了抽象方法caculate以外,还定义了一个默认方法sqrt。Formula的实现类只需要实现抽象方法caculate就可以了。默认方法sqrt可以直接使用。
1
2
3
4
5
6
7
8
9
|
Formula formula = new Formula() { @Override public double calculate( int a) { return sqrt(a * 100 ); } }; formula.calculate( 100 ); // 100.0 formula.sqrt( 16 ); // 4.0 |
formula对象以匿名对象的形式实现了Formula接口。代码很啰嗦:用了6行代码才实现了一个简单的计算功能:a*100开平方根。我们在下一节会看到,Java 8 还有一种更加优美的方法,能够实现包含单个函数的对象。
Lambda表达式
让我们从最简单的例子开始,来学习如何对一个string列表进行排序。我们首先使用Java 8之前的方法来实现:
1
2
3
4
5
6
7
8
|
List<String> names = Arrays.asList( "peter" , "anna" , "mike" , "xenia" ); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } }); |
静态工具方法Collections.sort接受一个list,和一个Comparator接口作为输入参数,Comparator的实现类可以对输入的list中的元素进行比较。通常情况下,你可以直接用创建匿名Comparator对象,并把它作为参数传递给sort方法。
除了创建匿名对象以外,Java 8 还提供了一种更简洁的方式,Lambda表达式。
1
2
3
|
Collections.sort(names, (String a, String b) -> { return b.compareTo(a); }); |
你可以看到,这段代码就比之前的更加简短和易读。但是,它还可以更加简短:
1
|
Collections.sort(names, (String a, String b) -> b.compareTo(a)); |
只要一行代码,包含了方法体。你甚至可以连大括号对{}和return关键字都省略不要。不过这还不是最短的写法:
1
|
Collections.sort(names, (a, b) -> b.compareTo(a)); |
Java编译器能够自动识别参数的类型,所以你就可以省略掉类型不写。让我们再深入地研究一下lambda表达式的威力吧。
函数式接口
Lambda表达式如何匹配Java的类型系统?每一个lambda都能够通过一个特定的接口,与一个给定的类型进行匹配。一个所谓的函数式接口必须要有且仅有一个抽象方法声明。每个与之对应的lambda表达式必须要与抽象方法的声明相匹配。由于默认方法不是抽象的,因此你可以在你的函数式接口里任意添加默认方法。
任意只包含一个抽象方法的接口,我们都可以用来做成lambda表达式。为了让你定义的接口满足要求,你应当在接口前加上@FunctionalInterface 标注。编译器会注意到这个标注,如果你的接口中定义了第二个抽象方法的话,编译器会抛出异常。
举例:
1
2
3
4
5
6
7
8
|
@FunctionalInterface interface Converter<F, T> { T convert(F from); } Converter<String, Integer> converter = (from) -> Integer.valueOf(from); Integer converted = converter.convert( "123" ); System.out.println(converted); // 123 |
注意,如果你不写@FunctionalInterface 标注,程序也是正确的。
方法和构造函数引用
上面的代码实例可以通过静态方法引用,使之更加简洁:
1
2
3
|
Converter<String, Integer> converter = Integer::valueOf; Integer converted = converter.convert( "123" ); System.out.println(converted); // 123 |
Java 8 允许你通过::关键字获取方法或者构造函数的的引用。上面的例子就演示了如何引用一个静态方法。而且,我们还可以对一个对象的方法进行引用:
1
2
3
4
5
6
7
8
9
10
|
class Something { String startsWith(String s) { return String.valueOf(s.charAt( 0 )); } } Something something = new Something(); Converter<String, String> converter = something::startsWith; String converted = converter.convert( "Java" ); System.out.println(converted); // "J" |
让我们看看如何使用::关键字引用构造函数。首先我们定义一个示例bean,包含不同的构造方法:
1
2
3
4
5
6
7
8
9
10
11
|
class Person { String firstName; String lastName; Person() {} Person(String firstName, String lastName) { this .firstName = firstName; this .lastName = lastName; } } |
接下来,我们定义一个person工厂接口,用来创建新的person对象:
1
2
3
|
interface PersonFactory<P extends Person> { P create(String firstName, String lastName); } |
然后我们通过构造函数引用来把所有东西拼到一起,而不是像以前一样,通过手动实现一个工厂来这么做。
1
2
|
PersonFactory<Person> personFactory = Person:: new ; Person person = personFactory.create( "Peter" , "Parker" ); |
我们通过Person::new来创建一个Person类构造函数的引用。Java编译器会自动地选择合适的构造函数来匹配PersonFactory.create函数的签名,并选择正确的构造函数形式。
Lambda的范围
对于lambdab表达式外部的变量,其访问权限的粒度与匿名对象的方式非常类似。你能够访问局部对应的外部区域的局部final变量,以及成员变量和静态变量。
访问局部变量
我们可以访问lambda表达式外部的final局部变量:
1
2
3
4
5
|
final int num = 1 ; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert( 2 ); // 3 |
但是与匿名对象不同的是,变量num并不需要一定是final。下面的代码依然是合法的:
1
2
3
4
5
|
int num = 1 ; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert( 2 ); // 3 |
然而,num在编译的时候被隐式地当做final变量来处理。下面的代码就不合法:
1
2
3
4
|
int num = 1 ; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); num = 3 ; |
在lambda表达式内部企图改变num的值也是不允许的。
访问成员变量和静态变量
与局部变量不同,我们在lambda表达式的内部能获取到对成员变量或静态变量的读写权。这种访问行为在匿名对象里是非常典型的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Lambda4 { static int outerStaticNum; int outerNum; void testScopes() { Converter<Integer, String> stringConverter1 = (from) -> { outerNum = 23 ; return String.valueOf(from); }; Converter<Integer, String> stringConverter2 = (from) -> { outerStaticNum = 72 ; return String.valueOf(from); }; } } |
访问默认接口方法
还记得第一节里面formula的那个例子么? 接口Formula定义了一个默认的方法sqrt,该方法能够访问formula所有的对象实例,包括匿名对象。这个对lambda表达式来讲则无效。
默认方法无法在lambda表达式内部被访问。因此下面的代码是无法通过编译的:
1
|
Formula formula = (a) -> sqrt( a * 100 ); |
内置函数式接口
JDK 1.8 API中包含了很多内置的函数式接口。有些是在以前版本的Java中大家耳熟能详的,例如Comparator接口,或者Runnable接口。对这些现成的接口进行实现,可以通过@FunctionalInterface 标注来启用Lambda功能支持。
此外,Java 8 API 还提供了很多新的函数式接口,来降低程序员的工作负担。有些新的接口已经在Google Guava库中很有名了。如果你对这些库很熟的话,你甚至闭上眼睛都能够想到,这些接口在类库的实现过程中起了多么大的作用。
Predicates
Predicate是一个布尔类型的函数,该函数只有一个输入参数。Predicate接口包含了多种默认方法,用于处理复杂的逻辑动词(and, or,negate)
1
2
3
4
5
6
7
8
9
10
|
Predicate<String> predicate = (s) -> s.length() > 0 ; predicate.test( "foo" ); // true predicate.negate().test( "foo" ); // false Predicate<Boolean> nonNull = Objects::nonNull; Predicate<Boolean> isNull = Objects::isNull; Predicate<String> isEmpty = String::isEmpty; Predicate<String> isNotEmpty = isEmpty.negate(); |
Functions
Function接口接收一个参数,并返回单一的结果。默认方法可以将多个函数串在一起(compse, andThen)
1
2
3
4
|
Function<String, Integer> toInteger = Integer::valueOf; Function<String, String> backToString = toInteger.andThen(String::valueOf); backToString.apply( "123" ); // "123" |
Suppliers
Supplier接口产生一个给定类型的结果。与Function不同的是,Supplier没有输入参数。
1
2
|
Supplier<Person> personSupplier = Person:: new ; personSupplier.get(); // new Person |
Consumers
Consumer代表了在一个输入参数上需要进行的操作。
1
2
|
Consumer<Person> greeter = (p) -> System.out.println( "Hello, " + p.firstName); greeter.accept( new Person( "Luke" , "Skywalker" )); |
Comparators
Comparator接口在早期的Java版本中非常著名。Java 8 为这个接口添加了不同的默认方法。
1
2
3
4
5
6
7
|
Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person( "John" , "Doe" ); Person p2 = new Person( "Alice" , "Wonderland" ); comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // < 0 |
Optionals
Optional不是一个函数式接口,而是一个精巧的工具接口,用来防止NullPointerEception产生。这个概念在下一节会显得很重要,所以我们在这里快速地浏览一下Optional的工作原理。
Optional是一个简单的值容器,这个值可以是null,也可以是non-null。考虑到一个方法可能会返回一个non-null的值,也可能返回一个空值。为了不直接返回null,我们在Java 8中就返回一个Optional.
1
2
3
4
5
6
7
|
Optional<String> optional = Optional.of( "bam" ); optional.isPresent(); // true optional.get(); // "bam" optional.orElse( "fallback" ); // "bam" optional.ifPresent((s) -> System.out.println(s.charAt( 0 ))); // "b" |
Streams
java.util.Stream表示了某一种元素的序列,在这些元素上可以进行各种操作。Stream操作可以是中间操作,也可以是完结操作。完结操作会返回一个某种类型的值,而中间操作会返回流对象本身,并且你可以通过多次调用同一个流操作方法来将操作结果串起来(就像StringBuffer的append方法一样————译者注)。Stream是在一个源的基础上创建出来的,例如java.util.Collection中的list或者set(map不能作为Stream的源)。Stream操作往往可以通过顺序或者并行两种方式来执行。
我们先了解一下序列流。首先,我们通过string类型的list的形式创建示例数据:
1
2
3
4
5
6
7
8
9
|
List<String> stringCollection = new ArrayList<>(); stringCollection.add( "ddd2" ); stringCollection.add( "aaa2" ); stringCollection.add( "bbb1" ); stringCollection.add( "aaa1" ); stringCollection.add( "bbb3" ); stringCollection.add( "ccc" ); stringCollection.add( "bbb2" ); stringCollection.add( "ddd1" ); |
Java 8中的Collections类的功能已经有所增强,你可以之直接通过调用Collections.stream()或者Collection.parallelStream()方法来创建一个流对象。下面的章节会解释这个最常用的操作。
Filter
Filter接受一个predicate接口类型的变量,并将所有流对象中的元素进行过滤。该操作是一个中间操作,因此它允许我们在返回结果的基础上再进行其他的流操作(forEach)。ForEach接受一个function接口类型的变量,用来执行对每一个元素的操作。ForEach是一个中止操作。它不返回流,所以我们不能再调用其他的流操作。
1
2
3
4
5
6
|
stringCollection .stream() .filter((s) -> s.startsWith( "a" )) .forEach(System.out::println); // "aaa2", "aaa1" |
Sorted
Sorted是一个中间操作,能够返回一个排过序的流对象的视图。流对象中的元素会默认按照自然顺序进行排序,除非你自己指定一个Comparator接口来改变排序规则。
1
2
3
4
5
6
7
|
stringCollection .stream() .sorted() .filter((s) -> s.startsWith( "a" )) .forEach(System.out::println); // "aaa1", "aaa2" |
一定要记住,sorted只是创建一个流对象排序的视图,而不会改变原来集合中元素的顺序。原来string集合中的元素顺序是没有改变的。
1
2
|
System.out.println(stringCollection); // ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1 |
Map
map是一个对于流对象的中间操作,通过给定的方法,它能够把流对象中的每一个元素对应到另外一个对象上。下面的例子就演示了如何把每个string都转换成大写的string. 不但如此,你还可以把每一种对象映射成为其他类型。对于带泛型结果的流对象,具体的类型还要由传递给map的泛型方法来决定。
1
2
3
4
5
6
7
|
stringCollection .stream() .map(String::toUpperCase) .sorted((a, b) -> b.compareTo(a)) .forEach(System.out::println); // "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1" |
Match
匹配操作有多种不同的类型,都是用来判断某一种规则是否与流对象相互吻合的。所有的匹配操作都是终结操作,只返回一个boolean类型的结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
boolean anyStartsWithA = stringCollection .stream() .anyMatch((s) -> s.startsWith( "a" )); System.out.println(anyStartsWithA); // true boolean allStartsWithA = stringCollection .stream() .allMatch((s) -> s.startsWith( "a" )); System.out.println(allStartsWithA); // false boolean noneStartsWithZ = stringCollection .stream() .noneMatch((s) -> s.startsWith( "z" )); System.out.println(noneStartsWithZ); // true |
Count
Count是一个终结操作,它的作用是返回一个数值,用来标识当前流对象中包含的元素数量。
1
2
3
4
5
6
7
|
long startsWithB = stringCollection .stream() .filter((s) -> s.startsWith( "b" )) .count(); System.out.println(startsWithB); // 3 |
Reduce
该操作是一个终结操作,它能够通过某一个方法,对元素进行削减操作。该操作的结果会放在一个Optional变量里返回。
1
2
3
4
5
6
7
8
|
Optional<String> reduced = stringCollection .stream() .sorted() .reduce((s1, s2) -> s1 + "#" + s2); reduced.ifPresent(System.out::println); // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2" |
Parallel Streams
像上面所说的,流操作可以是顺序的,也可以是并行的。顺序操作通过单线程执行,而并行操作则通过多线程执行。
下面的例子就演示了如何使用并行流进行操作来提高运行效率,代码非常简单。
首先我们创建一个大的list,里面的元素都是唯一的:
1
2
3
4
5
6
|
int max = 1000000 ; List<String> values = new ArrayList<>(max); for ( int i = 0 ; i < max; i++) { UUID uuid = UUID.randomUUID(); values.add(uuid.toString()); } |
现在,我们测量一下对这个集合进行排序所使用的时间。
顺序排序
1
2
3
4
5
6
7
8
9
10
11
|
long t0 = System.nanoTime(); long count = values.stream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format( "sequential sort took: %d ms" , millis)); // sequential sort took: 899 ms |
并行排序
1
2
3
4
5
6
7
8
9
10
11
|
long t0 = System.nanoTime(); long count = values.parallelStream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format( "parallel sort took: %d ms" , millis)); // parallel sort took: 472 ms |
如你所见,所有的代码段几乎都相同,唯一的不同就是把stream()改成了parallelStream(), 结果并行排序快了50%。
Map
正如前面已经提到的那样,map是不支持流操作的。而更新后的map现在则支持多种实用的新方法,来完成常规的任务。
1
2
3
4
5
6
7
|
Map<Integer, String> map = new HashMap<>(); for ( int i = 0 ; i < 10 ; i++) { map.putIfAbsent(i, "val" + i); } map.forEach((id, val) -> System.out.println(val)); |
上面的代码风格是完全自解释的:putIfAbsent避免我们将null写入;forEach接受一个消费者对象,从而将操作实施到每一个map中的值上。
下面的这个例子展示了如何使用函数来计算map的编码
1
2
3
4
5
6
7
8
9
10
11
|
map.computeIfPresent( 3 , (num, val) -> val + num); map.get( 3 ); // val33 map.computeIfPresent( 9 , (num, val) -> null ); map.containsKey( 9 ); // false map.computeIfAbsent( 23 , num -> "val" + num); map.containsKey( 23 ); // true map.computeIfAbsent( 3 , num -> "bam" ); map.get( 3 ); // val33 |
接下来,我们将学习,当给定一个key值时,如何把一个实例从对应的key中移除:
1
2
3
4
5
|
map.remove( 3 , "val3" ); map.get( 3 ); // val33 map.remove( 3 , "val33" ); map.get( 3 ); // null |
另一个有用的方法:
1
|
map.getOrDefault( 42 , "not found" ); // not found |
将map中的实例合并也是非常容易的:
1
2
3
4
5
|
map.merge( 9 , "val9" , (value, newValue) -> value.concat(newValue)); map.get( 9 ); // val9 map.merge( 9 , "concat" , (value, newValue) -> value.concat(newValue)); map.get( 9 ); // val9concat |
合并操作先看map中是否没有特定的key/value存在,如果是,则把key/value存入map,否则merging函数就会被调用,对现有的数值进行修改。
时间日期API
Java 8 包含了全新的时间日期API,这些功能都放在了java.time包下。新的时间日期API是基于Joda-Time库开发的,但是也不尽相同。下面的例子就涵盖了大多数新的API的重要部分。
Clock
Clock提供了对当前时间和日期的访问功能。Clock是对当前时区敏感的,并可用于替代System.currentTimeMillis()方法来获取当前的毫秒时间。当前时间线上的时刻可以用Instance类来表示。Instance也能够用于创建原先的java.util.Date对象。
1
2
3
4
5
|
Clock clock = Clock.systemDefaultZone(); long millis = clock.millis(); Instant instant = clock.instant(); Date legacyDate = Date.from(instant); // legacy java.util.Date |
Timezones
时区类可以用一个ZoneId来表示。时区类的对象可以通过静态工厂方法方便地获取。时区类还定义了一个偏移量,用来在当前时刻或某时间与目标时区时间之间进行转换。
1
2
3
4
5
6
7
8
9
10
|
System.out.println(ZoneId.getAvailableZoneIds()); // prints all available timezone ids ZoneId zone1 = ZoneId.of( "Europe/Berlin" ); ZoneId zone2 = ZoneId.of( "Brazil/East" ); System.out.println(zone1.getRules()); System.out.println(zone2.getRules()); // ZoneRules[currentStandardOffset=+01:00] // ZoneRules[currentStandardOffset=-03:00] |
LocalTime
本地时间类表示一个没有指定时区的时间,例如,10 p.m.或者17:30:15,下面的例子会用上面的例子定义的时区创建两个本地时间对象。然后我们会比较两个时间,并计算它们之间的小时和分钟的不同。
1
2
3
4
5
6
7
8
9
10
|
LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2); System.out.println(now1.isBefore(now2)); // false long hoursBetween = ChronoUnit.HOURS.between(now1, now2); long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); System.out.println(hoursBetween); // -3 System.out.println(minutesBetween); // -239 |
LocalTime是由多个工厂方法组成,其目的是为了简化对时间对象实例的创建和操作,包括对时间字符串进行解析的操作。
1
2
3
4
5
6
7
8
9
10
|
LocalTime late = LocalTime.of( 23 , 59 , 59 ); System.out.println(late); // 23:59:59 DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedTime(FormatStyle.SHORT) .withLocale(Locale.GERMAN); LocalTime leetTime = LocalTime.parse( "13:37" , germanFormatter); System.out.println(leetTime); // 13:37 |
LocalDate
本地时间表示了一个独一无二的时间,例如:2014-03-11。这个时间是不可变的,与LocalTime是同源的。下面的例子演示了如何通过加减日,月,年等指标来计算新的日期。记住,每一次操作都会返回一个新的时间对象。
1
2
3
4
5
6
7
|
LocalDate today = LocalDate.now(); LocalDate tomorrow = today.plus( 1 , ChronoUnit.DAYS); LocalDate yesterday = tomorrow.minusDays( 2 ); LocalDate independenceDay = LocalDate.of( 2014 , Month.JULY, 4 ); DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); System.out.println(dayOfWeek); // FRIDAY<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">Parsing a LocalDate from a string is just as simple as parsing a LocalTime:</span> |
解析字符串并形成LocalDate对象,这个操作和解析LocalTime一样简单。
1
2
3
4
5
6
7
|
DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedDate(FormatStyle.MEDIUM) .withLocale(Locale.GERMAN); LocalDate xmas = LocalDate.parse( "24.12.2014" , germanFormatter); System.out.println(xmas); // 2014-12-24 |
LocalDateTime
LocalDateTime表示的是日期-时间。它将刚才介绍的日期对象和时间对象结合起来,形成了一个对象实例。LocalDateTime是不可变的,与LocalTime和LocalDate的工作原理相同。我们可以通过调用方法来获取日期时间对象中特定的数据域。
1
2
3
4
5
6
7
8
9
10
|
LocalDateTime sylvester = LocalDateTime.of( 2014 , Month.DECEMBER, 31 , 23 , 59 , 59 ); DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); System.out.println(dayOfWeek); // WEDNESDAY Month month = sylvester.getMonth(); System.out.println(month); // DECEMBER long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY); System.out.println(minuteOfDay); // 1439 |
如果再加上的时区信息,LocalDateTime能够被转换成Instance实例。Instance能够被转换成以前的java.util.Date对象。
1
2
3
4
5
6
|
Instant instant = sylvester .atZone(ZoneId.systemDefault()) .toInstant(); Date legacyDate = Date.from(instant); System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014 |
格式化日期-时间对象就和格式化日期对象或者时间对象一样。除了使用预定义的格式以外,我们还可以创建自定义的格式化对象,然后匹配我们自定义的格式。
1
2
3
4
5
6
7
|
DateTimeFormatter formatter = DateTimeFormatter .ofPattern( "MMM dd, yyyy - HH:mm" ); LocalDateTime parsed = LocalDateTime.parse( "Nov 03, 2014 - 07:13" , formatter); String string = formatter.format(parsed); System.out.println(string); // Nov 03, 2014 - 07:13 |
不同于java.text.NumberFormat,新的DateTimeFormatter类是不可变的,也是线程安全的。
更多的细节,请看这里
Annotations
Java 8中的注解是可重复的。让我们直接深入看看例子,弄明白它是什么意思。
首先,我们定义一个包装注解,它包括了一个实际注解的数组
1
2
3
4
5
6
7
8
|
@interface Hints { Hint[] value(); } @Repeatable (Hints. class ) @interface Hint { String value(); } |
只要在前面加上注解名:@Repeatable,Java 8 允许我们对同一类型使用多重注解,
变体1:使用注解容器(老方法)
1
2
|
@Hints ({ @Hint ( "hint1" ), @Hint ( "hint2" )}) class Person {} |
变体2:使用可重复注解(新方法)
1
2
3
|
@Hint ( "hint1" ) @Hint ( "hint2" ) class Person {} |
使用变体2,Java编译器能够在内部自动对@Hint进行设置。这对于通过反射来读取注解信息来说,是非常重要的。
1
2
3
4
5
6
7
8
|
Hint hint = Person. class .getAnnotation(Hint. class ); System.out.println(hint); // null Hints hints1 = Person. class .getAnnotation(Hints. class ); System.out.println(hints1.value().length); // 2 Hint[] hints2 = Person. class .getAnnotationsByType(Hint. class ); System.out.println(hints2.length); // 2 |
尽管我们绝对不会在Person类上声明@Hints注解,但是它的信息仍然可以通过getAnnotation(Hints.class)来读取。并且,getAnnotationsByType方法会更方便,因为它赋予了所有@Hints注解标注的方法直接的访问权限。
1
2
|
@Target ({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) @interface MyAnnotation {} |
先到这里
我的Java 8编程指南就到此告一段落。当然,还有很多内容需要进一步研究和说明。这就需要靠读者您来对JDK 8进行探究了,例如:Arrays.parallelSort, StampedLock和CompletableFuture等等 ———— 我这里只是举几个例子而已。
我希望这个博文能够对您有所帮助,也希望您阅读愉快。完整的教程源代码放在了GitHub上。您可以尽情地fork,并请通过Twitter告诉我您的反馈。
原文链接: winterbe 翻译: ImportNew.com – 黄小非
译文链接: http://www.importnew.com/10360.html
100+ Core Java Interview Questions
Table of Contents
- Basic Questions
- OOPs interview Questions
- Exception handling interview Questions
- Java Multithreading interview Questions
- Serialization interview Questions
- String Interview Questions
- Java Collections interview Questions
- Applet interview Questions
Basic Questions
Q) Is Java platform independent?
Yes. Java is a platform independent language. We can write java code on one platform and run it on another platform. For e.g. we can write and compile the code on windows and can run it on Linux or any other supported platform. This is one of the main features of java.
Q) What all memory areas are allocated by JVM?
Heap, Stack, Program Counter Register and Native Method Stack
Q) Java vs. C ++?
The following features of java make it different from the C++:
- Simple
- Multi-threaded
- Distributed Application
- Robust
- Security
- Complexities are removed (Pointers, Operator overloading, Multiple inheritance).
Q) What is javac ?
It produces the java byte code from *.java file. It is the intermediate representation of your source code that contains instructions.
Q) What is class?
Class is nothing but a template that describes the data and behavior associated with instances of that class
Q) What is the base class of all classes?
java.lang.Object
Q) Path and ClassPath
Path specifies the location of .exe files while classpath is used for specifying the location of .class files.
Q) Different Data types in Java.
- byte – 8 bit (are esp. useful when working with a stream of data from a network or a file).
- short – 16 bit
- char – 16 bit Unicode
- int – 32 bit (whole number)
- float – 32 bit (real number)
- long – 64 bit (Single precision)
- double – 64 bit (double precision)
Note: Any time you have an integer expression involving bytes, shorts, ints and literal numbers, the entire expression is promoted to int before the calculation is done.
Q) What is Unicode?
Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages.
Q) What are Literals?
A literal is a value that may be assigned to a primitive or string variable or passed as an argument to a method.
Q) Dynamic Initialization?
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
Q) What is Type casting in Java?
To create a conversion between two incompatible types, we must use a cast. There are two types of casting in java: automatic casting (done automatically) and explicit casting (done by programmer).
Q) Arrays?
An array is a group of fixed number of same type values. Read more about Arrays here.
Q) What is BREAK statement in java?
It is also referred as terminator. In Java, the break statement can be used in following two cases:
- It terminates a statement sequence in a switch-case statement.
- It can be used to come out of a loop
Q) Why can’t I do myArray.length () ? Arrays are just objects, right?
Yes, the specification says that arrays are object references just like classes are. You can even invoke the methods of Object such as toString () and hashCode () on an array. However, length is a data item of an array and not a method. So you have to use myArray.length.
Q) How can I put all my classes and resources into one file and run it?
Use a JAR file. Put all the files in a JAR, then run the app like this:
Java -jar [-options] jarfile [args...]
Q) Can I declare a data type inside loop in java?
Any Data type declaration should not be inside the loop.
Q) Advantage over jdk 1.0 vs. jdk 1.1 ?
Jdk1.1 release consists of Java Unicode character to support the multiple language fonts, along with Event Handling, Java security, Java Beans, RMI, SQL are the major feature provided.
Q) java.lang.* get imported by default. For using String and Exception classes, you don’t need to explicitly import this package. The major classes inside this package are
- Object class
- Data type wrapper classes
- Math class
- String class
- System and Runtime classes
- Thread classes
- Exception classes
- Process classes
- Class classes
Q) Arrays can be defined in different ways. Write them down.
int arr[] = null; int arr[][] = new int arr[][]; int [][] arr = new arr [][]; int [] arr [] = new arr[][];
OOPs Interview Questions
Q) Four main principles of OOPS language?
- Inheritance
- Polymorphism
- Data Encapsulation
- Abstraction
Q) What is inheritance?
The process by which one class acquires the properties and functionalities of another class. Inheritance brings reusability of code in a java application. Read more here.
Q) Does Java support Multiple Inheritances?
When a class extends more than one classes then it is called multiple inheritance. Java doesn’t support multiple inheritance whereas C++ supports it, this is one of the difference between java and C++. Refer this: Why java doesn’t support multiple inheritance?
Q) What is Polymorphism and what are the types of it?
Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: static polymorphism and dynamic polymorphism, read them in detail here.
Q) What is the method overriding?
It is a feature using which a child class overrides the method of parent class. It is only applicable when the method in child class has the signature same as parent class. Read more about method overriding here.
Q) Can we override a static method?
No, we cannot override a static method.
Q) What is method overloading?
Having more than one method with the same name but different number, sequence or types of arguments is known is method overloading. Read more about it here.
Q) Does Java support operator overloading?
Operator overloading is not supported in Java.
Q) Can we overload a method by just changing the return type and without changing the signature of method?
No, We cannot do this.
Q) Is it possible to overload main() method of a class?
Yes, we can overload main() method as well.
Q) What is the difference between method overloading and method overriding?
There are several differences; You can read them here: Overloading Vs Overriding.
Q) What is static and dynamic binding?
Binding refers to the linking of method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding.
Q) What is Encapsulation?
Encapsulation means the localization of the information or knowledge within an object.
Encapsulation is also called as “Information Hiding”. Read it here in detail.
Q) Abstract class?
An abstract class is a class which can’t be instantiated (we cannot create the object of abstract class), we can only extend such classes. It provides the generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. We can achieve partial abstraction using abstract classes, to achieve full abstraction we use interfaces.
Q) What is Interface in java?
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Read more about interface here.
Q) What is the difference between abstract class and interface?
1) abstract class can have abstract and non-abstract methods. An interface can only have abstract methods.
2) An abstract class can have static methods but an interface cannot have static methods.
3) abstract class can have constructors but an interface cannot have constructors.
Q) Which access modifiers can be applied to the inner classes?
public ,private , abstract, final, protected.
Q) What are Constructors?
Constructors are used for creating an instance of a class, they are invoked when an instance of class gets created. Constructor name and class name should be same and it doesn’t have a return type. Read more about constructors here.
Q) Can we inherit the constructors?
No, we cannot inherit constructors.
Q) Can we mark constructors final?
No, Constructor cannot be declared final.
Q) What is default and parameterized constructors?
Default: Constructors with no arguments are known as default constructors, when you don’t declare any constructor in a class, compiler creates a default one automatically.
Parameterized: Constructor with arguments are known as parameterized constructors.
Q) Can a constructor call another constructor?
Yes. A constructor can call the another constructor of same class using this keyword. For e.g. this() calls the default constructor.
Note: this() must be the first statement in the calling constructor.
Q) Can a constructor call the constructor of parent class?
Yes. In fact it happens by default. A child class constructor always calls the parent class constructor. However we can still call it using super keyword. For e.g. super() can be used for calling super class default constructor.
Note: super() must be the first statement in a constructor.
Q)THIS keyword?
The THIS keyword is a reference to the current object.
Q) Can this keyword be assigned null value?
No, this keyword cannot have null values assigned to it.
Q) Explain ways to pass the arguments in Java?
In java, arguments can be passed in 2 ways,
Pass by value – Changes made to the parameter of the subroutines have no effect on the argument used to call it.
Pass by reference – Changes made to the parameter will affect the argument used to call the subroutine.
Q) What is static variable in java?
Static variables are also known as class level variables. A static variable is same for all the objects of that particular class in which it is declared.
Q) What is static block?
A static block gets executed at the time of class loading. They are used for initializing static variables.
Q) What is a static method?
Static methods can be called directly without creating the instance (Object) of the class. A static method can access all the static variables of a class directly but it cannot access non-static variables without creating instance of class.
Q) Explain super keyword in Java?
super keyword references to the parent class. There are several uses of super keyword:
- It can be used to call the superclass(Parent class) constructor.
- It can be used to access a method of the superclass that has been hidden by subclass (Calling parent class version, In case of method overriding).
- To call the constructor of parent class.
Q) Use of final keyword in Java?
Final methods – These methods cannot be overridden by any other method.
Final variable – Constants, the value of these variable can’t be changed, its fixed.
Final class – Such classes cannot be inherited by other classes. These type of classes will be used when application required security or someone don’t want that particular class. More details.
Q) What is a Object class?
This is a special class defined by java; all other classes are subclasses of object class. Object class is superclass of all other classes. Object class has the following methods
- objectClone () – to creates a new object that is same as the object being cloned.
- boolean equals(Object obj) – determines whether one object is equal to another.
- finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
- toString () – Returns a string representation of the object.
Q) What are Packages?
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations )
Q)What is the difference between import java.util.Date and java.util.* ?
The star form (java.util.* ) includes all the classes of that package and that may increase the compilation time – especially if you import several packages. However it doesn’t have any effect run-time performance.
Q) What is static import?
Read it here.
Q) Garbage collection in java?
Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically when no references to an object exist for a long time is called garbage collection. The whole purpose of Garbage collection is efficient memory management.
Q) Use of finalize() method in java?
finalize() method is used to free the allocated resource.
Q) How many times does the garbage collector calls the finalize() method for an object?
The garbage collector calls the finalize() method Only once for an object.
Q) What are two different ways to call garbage collector?
System.gc()
OR Runtime.getRuntime().gc()
.
Q) Can the Garbage Collection be forced by any means?
No, its not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.
Exception handling Interview Questions
Q) What is an exception?
Exceptions are abnormal conditions that arise during execution of the program. It may occur due to wrong user input or wrong logic written by programmer.
Q) Exceptions are defined in which java package? OR which package has definitions for all the exception classes?
Java.lang.Exception
This package contains definitions for Exceptions.
Q) What are the types of exceptions?
There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.
Q) What is the difference between Error and Exception?
Error: Mostly a system issue. It always occur at run time and must be resolved in order to proceed further.
Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.
Q) What is throw keyword in exception handling?
The throw keyword is used for throwing user defined or pre-defined exception.
Q) What is throws keyword?
If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method’s signature.
Q) Difference between throw and throws in Java
Read the difference here: Java – throw vs throws.
Q) Can static block throw exception?
Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.
Q) What is finally block?
Finally block is a block of code that always executes, whether an exception occurs or not. Finally block follows try block or try-catch block.
Q) ClassNotFoundException vs NoClassDefFoundError?
1) ClassNotFoundException occurs when loader could not find the required class in class path.
2) NoClassDefFoundError occurs when class is loaded in classpath, but one or more of the class which are required by other class, are removed or failed to load by compiler.
Q) Can we have a try block without catch or finally block?
No, we cannot have a try block without catch or finally block. We must have either one of them or both.
Q) Can we have multiple catch blocks following a single try block?
Yes we can have multiple catch blocks in order to handle more than one exception.
Q) Is it possible to have finally block without catch block?
Yes, we can have try block followed by finally block without even using catch blocks in between.
When a finally block does not get executed?
The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.
Q) Can we handle more than one exception in a single catch block?
Yes we can do that using if-else statement but it is not considered as a good practice. We should have one catch block for one exception.
Q) What is a Java Bean?
A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.
Java Multithreading Interview Questions
Q) What is Multithreading?
It is a process of executing two or more part of a program simultaneously. Each of these parts is known as threads. In short the process of executing multiple threads simultaneously is known as multithreading.
Q) What is the main purpose of having multithread environment?
Maximizing CPU usage and reducing CPU idle time
Q) What are the main differences between Process and thread? Explain in brief.
1) One process can have multiple threads. A thread is a smaller part of a process.
2) Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and shares it with other threads.
3) Threads of same process can communicate with each other using keyword like wait and notify etc. This process is known as inter process communication.
Q) How can we create a thread in java?
There are following two ways of creating a thread:
1) By Implementing Runnable interface.
2) By Extending Thread class.
Q) Explain yield and sleep?
yield() – It causes the currently executing thread object to temporarily pause and allow other threads to execute.
sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock.
Q) What is the difference between sleep() and wait()?
sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock
wait() – It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
Q) What is a daemon thread?
A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.
Q) What does join( ) method do?
if you use join() ,it makes sure that as soon as a thread calls join,the current thread(yes,currently running thread) will not execute unless the thread you have called join is finished.
Q) Preemptive scheduling vs. time slicing?
1) The preemptive scheduling is prioritized. The highest priority process should always be the process that is currently utilized.
2) Time slicing means task executes for a defined slice/ period of time and then enter in the pool of ready state. The scheduler then determines which task execute next based on priority or other factor.
Q) Can we call run() method of a Thread class?
Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, you should call Thread.start() method to start it.
Q) What is Starvation?
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by “greedy” threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.
Q) What is deadlock?
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
Serialization interview Questions
Q: What is Serialization and de-serialization?
Serialization is a process of converting an object and its attributes to the stream of bytes. De-serialization is recreating the object from stream of bytes; it is just a reverse process of serialization. To know more about serialization with example program, refer this article.
Q) Do we need to implement any method of Serializable interface to make an object serializable?
No. In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods.
Q) What is a transient variable?
1) transient variables are not included in the process of serialization.
2) They are not the part of the object’s serialized state.
3) Variables which we don’t want to include in serialization are declared as transient.
String interview questions
Q) A string class is immutable or mutable?
String class is immutable that’s the reason once its object gets created, it cannot be changed further.
Q) Difference between StringBuffer and StringBuilder class?
1) StringBuffer is thread-safe but StringBuilder is not thread safe.
2) StringBuilder is faster than StringBuffer.
3) StringBuffer is synchronized whereas StringBuilder is not synchronized.
Q) What is toString() method in Java?
The toString() method returns the string representation of any object.
Java collections interview questions
Q) What is List?
Elements can be inserted or accessed by their position in the list, using a zero-based index.
A list may contain duplicate elements.
Q) What is Map?
Map interface maps unique keys to values. A key is an object that we use to retrieve a value later. A map cannot contain duplicate keys: Each key can map to at most one value.
Q) What is Set?
A Set is a Collection that cannot contain duplicate elements.
Q) Why ArrayList is better than Arrays?
Array can hold fixed number of elements. ArrayList can grow dynamically.
Q) What is the difference between ArrayList and LinkedList?
1) LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
2) LinkedList is preferred for add and update operations while ArrayList is a good choice for search operations. Read more here.
Q) For addition and deletion. Which one is most preferred: ArrayList or LinkedList?
LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.
Q) For searches. Which one is most preferred: ArrayList or LinkedList?
ArrayList. Searching an element is faster in ArrayList compared to LinkedList.
Q) What is the difference between ArrayList and Vector?
1) Vector is synchronized while ArrayList is not synchronized.
2) By default, Vector doubles the size of its array when it is re-sized internally. ArrayList increases by half of its size when it is re-sized. More details.
Q) What is the difference between Iterator and ListIterator?
Following are the major differences between them:
1) Iterator can be used for traversing Set, List and Map. ListIterator can only be used for traversing a List.
2) We can traverse only in forward direction using Iterator. ListIterator can be used for traversing in both the directions(forward and backward). Read more at: ListIterator vs Iterator.
Q) Difference between TreeSet and SortedSet?
TreeSet implements SortedSet interface.
Q) What is the difference between HashMap and Hashtable?
1) Hashtable is synchronized. HashMap is not synchronized.
2) Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. Read more here.
Q) What is the difference between Iterator and Enumeration?
1) Iterator allows to remove elements from the underlying collection during the iteration using its remove() method. We cannot add/remove elements from a collection when using enumerator.
2) Iterator has improved method names.
Enumeration.hasMoreElement() -> Iterator.hasNext()
Enumeration.nextElement() -> Iterator.next().
Applet Interview Questions
Q) How do you do file I/O from an applet?
Unsigned applets are simply not allowed to read or write files on the local file system .
Unsigned applets can, however, read (but not write) non-class files bundled with your applet on the server, called resource files
Q) What is container ?
A component capable of holding another component is called as container.
Container
Panel
Applet
Window
Frame
Dialog
Learning)
- Flow Layout is default for panel.
- Border Layout is default for Frames.
Q) On Windows, generally frames are invisible, how to make it visible. ?
Frame f = new Frame(); f.setSize(300,200); //height and width f.setVisible(true) ; // Frames appears
Q) JFC – Java Foundation Class
Swing
AWT
Java2D
Drag and Drop
Accessibility
Learning) Listeners and Methods?
ActionListerner – actionPerformed();
ItemListerner – itemStateChanged();
TextListener – textValueChanged();
FocusListener – focusLost(); & FocusGained();
WindowListener – windowActified(); windowDEactified(); windowIconified(); windowDeiconified(); windowClosed(); windowClosing(); windowOpened();
MouseMotionListener – mouseDragged(); & mouseMoved();
MouseListener – mousePressed(); mouseReleased(); mouseEntered(); mouseExited(); mouseClicked();
Learnings)
parseInt – to convert string to int.
getBytes – string to byte array
Q) Applet Life cycle?
Following stage of any applets life cycle, starts with init(), start(), paint(), stop() and destroy().
Q) showStatus() ?–
To display the message at the bottom of the browser when applet is started.
Q) What is the Event handling?
Is irrespective of any component, if any action performed/done on Frame, Panel or on window, handling those actions are called Event Handling.
Q) What is Adapter class?
Adapter class is an abstract class.
Advantage of adapter: To perform any window listener, we need to include all the methods used by the window listener whether we use those methods are not in our class like Interfaces whereas with adapter class, its sufficient to include only the methods required to override. Straight opposite to Interface.
Further readings:
If you have finished reading above interview questions then you can go through the below tutorials to sharpen your knowledge in java. We will keep adding new question and answers to the above list.
1) Java Collection tutorial
2) Core Java concepts
3) OOPs concepts
4) Java Multithreading
5) String class and its methods
6) Java Exception handling
from:http://beginnersbook.com/2013/05/java-interview-questions/
Java Learning Resources
Sites:
The most popular website in the programming world with millions of good questions and answers
中国版的stackoverflow
Where software is built
The best site for video lectures.
The largest Tutorials Library on the web
Online Compiler and IDE >> C/C++, Java, PHP, Python, Perl and 40+ other compilers and interpreters
DZone
https://dzone.com/
Java SE Technical Documentation
http://docs.oracle.com/javase/8/
Java World
http://www.javaworld.com/
IBM developerWorks
http://www.ibm.com/developerworks/java/
Program Creek:one of the top 100 Java blogs
http://www.programcreek.com/
javased :Code examples for popular API classes
http://www.javased.com/
LeetCode
https://leetcode.com/
The top 100 Java blogs
100 High-Quality Java Developers’ Blogs
winterbe Blog
http://winterbe.com/
——————————————————
Books:
Thinking in Java (4th Edition)
Effective Java (2nd Edition)
Top 10 Books For Advanced Level Java Developers
Javalobby Readers’ Choice: Top Java Books
Knowledge:
Java Language and Virtual Machine Specifications
JVM:
深入理解JVM
https://segmentfault.com/a/1190000004206269
JVM Internals
http://blog.jamesdbloom.com/JVMInternals.html
*Top 8 Diagrams for Understanding Java
Java Code To Byte Code
http://blog.jamesdbloom.com/JavaCodeToByteCode_PartOne.html
refer:
http://www.programcreek.com/2013/09/top-10-websites-for-advanced-level-java-developers/
Checkstyle custom rule
1、找到本地eclipse所在工作目录{WorkSpace}
2、checkstyle rule的目录:{WorkSpace}\.metadata\.plugins\net.sf.eclipsecs.core
3、internal_config_xxxxx.xml 替换其中的内容如下(最好先新增一个自定义规则再替换,不要覆盖默认的规则)
Sample:
<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE module PUBLIC “-//Puppy Crawl//DTD Check Configuration 1.3//EN” “http://www.puppycrawl.com/dtds/configuration_1_3.dtd”>
<!–
This configuration file was written by the eclipse-cs plugin configuration editor
–>
<!–
Checkstyle-Configuration: Cpus
Description: none
–>
<module name=”Checker”>
<property name=”severity” value=”warning”/>
<module name=”TreeWalker”>
<module name=”CyclomaticComplexity”>
<property name=”max” value=”20″/>
</module>
<module name=”MethodLength”>
<property name=”max” value=”100″/>
</module>
<module name=”TypeName”>
<message key=”name.invalidPattern” value=”Type name ”{0}” must match pattern ”{1}”.”/>
</module>
<module name=”ClassTypeParameterName”>
<property name=”format” value=”(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)”/>
<message key=”name.invalidPattern” value=”Class type name ”{0}” must match pattern ”{1}”.”/>
</module>
<module name=”MethodTypeParameterName”>
<property name=”format” value=”(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)”/>
<message key=”name.invalidPattern” value=”Method type name ”{0}” must match pattern ”{1}”.”/>
</module>
<module name=”AnnotationLocation”>
<property name=”tokens” value=”VARIABLE_DEF”/>
<property name=”allowSamelineMultipleAnnotations” value=”true”/>
</module>
<module name=”JavadocMethod”>
<property name=”allowMissingParamTags” value=”true”/>
<property name=”allowMissingThrowsTags” value=”true”/>
<property name=”allowMissingReturnTag” value=”true”/>
<property name=”suppressLoadErrors” value=”true”/>
</module>
<module name=”BooleanExpressionComplexity”>
<property name=”max” value=”4″/>
</module>
<module name=”JavaNCSS”/>
<module name=”LineLength”>
<property name=”max” value=”100″/>
<property name=”tabWidth” value=”4″/>
</module>
<module name=”Indentation”>
<property name=”severity” value=”ignore”/>
<metadata name=”net.sf.eclipsecs.core.lastEnabledSeverity” value=”inherit”/>
</module>
<module name=”LeftCurly”/>
<module name=”NoWhitespaceBefore”/>
<module name=”PackageName”>
<property name=”format” value=”^[a-z]+(\.[a-z_][a-z0-9_]*)*$”/>
</module>
<module name=”ConstantName”/>
<module name=”LocalVariableName”/>
<module name=”MemberName”/>
<module name=”MethodName”/>
<module name=”PackageDeclaration”/>
<module name=”OneStatementPerLine”/>
<module name=”AvoidStarImport”/>
<module name=”ArrayTypeStyle”/>
<module name=”FallThrough”/>
<module name=”JavadocType”/>
<module name=”WhitespaceAround”>
<property name=”tokens” value=”ASSIGN,BAND,BAND_ASSIGN,BOR,BOR_ASSIGN,BSR,BSR_ASSIGN,BXOR,BXOR_ASSIGN,COLON,DIV,DIV_ASSIGN,DO_WHILE,EQUAL,GE,GT,LAND,LCURLY,LE,LITERAL_ASSERT,LITERAL_CATCH,LITERAL_DO,LITERAL_ELSE,LITERAL_FINALLY,LITERAL_FOR,LITERAL_IF,LITERAL_RETURN,LITERAL_SYNCHRONIZED,LITERAL_TRY,LITERAL_WHILE,LOR,LT,MINUS,MINUS_ASSIGN,MOD,MOD_ASSIGN,NOT_EQUAL,PLUS,PLUS_ASSIGN,RCURLY,SL,SLIST,SL_ASSIGN,SR,SR_ASSIGN,STAR,STAR_ASSIGN,TYPE_EXTENSION_AND,WILDCARD_TYPE”/>
<property name=”allowEmptyConstructors” value=”true”/>
<property name=”allowEmptyMethods” value=”true”/>
<property name=”allowEmptyTypes” value=”true”/>
<property name=”allowEmptyLoops” value=”true”/>
</module>
</module>
<module name=”FileLength”>
<property name=”max” value=”1000″/>
</module>
</module>