要求接口中只有一个抽象方法。
匿名内部类连抽象类都可以的。
public class EatableDemo {
public static void main(String[] args) {
Eatable eatStac = new EatStac();//实现接口
useEatable(eatStac);
//匿名内部类(实际工作不推荐使用)
useEatable(new Eatable() {
@Override
public void eat() {
System.out.println(120);
}
});
//lambda表达式
useEatable(()->{
System.out.println(120);
});
}
private static void useEatable(Eatable e){
e.eat();
}
}
//无参
//有参
public class FlyableDemo {
public static void main(String[] args) {
//匿名内部类
useFlyable(new Flyable() {
@Override
public void fly(String s) {
System.out.println(s);
System.out.println("坠毁");
}
});
//lambda
useFlyable((String s)->{
System.out.println(s);
System.out.println("坠毁");
});
}
private static void useFlyable(Flyable f){
f.fly("起飞。");
}
}
public class AddableDemo {
public static void main(String[] args) {
useAddable((int x,int y)->{
return x+y;
});
}
private staticvoid useAddable(Addable a){
int sum=a.add(4,5);
System.out.println(sum);
}
}
public class InterDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("1234");
list.add("12345");
list.add("123");
list.add("1");
System.out.println(list);
Collections.sort(list,getComparator());
System.out.println(list);
}
private static Comparator<String> getComparator(){
//三次简化。
// Comparator stringComparator = new Comparator(){
// @Override
// public int compare(String o1, String o2) {
// return o1.length()-o2.length();
// }
// };
// return stringComparator;
// return new Comparator(){
// @Override
// public int compare(String o1, String o2) {
// return o1.length()-o2.length();
// }
// };
// return (String s1,String s2)->{
// return s1.length()-s2.length();
// };
return (s1,s2)-> s1.length()-s2.length();
}
}
Functional Interface:
这是一个功能界面,因此可以用作lambda表达式或方法引用的赋值对象
所有方法:test,or,and,isEqual , negate(逻辑非)
通常用于判断参数是否满足特定的条件。
public class InterDemo {
public static void main(String[] args) {
boolean b = getComparator("123", (s) -> {
return s.length() >= 5;
});
boolean b1 = getComparator("123456", (s) -> {
return s.length() >= 5;
});
System.out.println(b);
System.out.println(b1);
}
private static boolean getComparator(String s, Predicate<String> predicate){
return predicate.test(s);
//return predicate.negate().test(s);
}
}
public class InterDemo {
public static void main(String[] args) {
boolean b1 = getComparator("13588", s -> {
return s.length() > 2;
}, s -> {
return s.startsWith("1");
});
boolean b2= getComparator("23588", s -> {
return s.length() > 2;
}, s -> {
return s.startsWith("1");
});
System.out.println(b1);//ture
System.out.println(b2);//false
}
private static boolean getComparator(String s, Predicate<String> predicate,Predicate<String> pr2) {
return predicate.and(pr2).test(s);
}
}
public class InterDemo {
public static void main(String[] args) {
String[] strArray={"林青霞,30","柳岩,34","张曼玉,35","貂蝉,31","王祖贤,33"};
ArrayList<String> list = new ArrayList<>();
for (String s: strArray
) {
if(getPredicate(s,a->{
return a.split(",")[0].length()>2;
},a->{
return Integer.parseInt(a.split(",")[1])>33;
})){
list.add(s);
}
}
System.out.println(list);
}
private static boolean getPredicate(String s,Predicate<String> p1,Predicate<String> p2){
return p1.and(p2).test(s);
}
}
public class InterDemo {
public static void main(String[] args) {
String[] strArray={"林青霞,30","柳岩,34","张曼玉,35","貂蝉,31","王祖贤,33"};
ArrayList<String> list = getPredicate(strArray,s->{
return s.split(",")[0].length()>2;
},s->{
return Integer.parseInt(s.split(",")[1])>33;
});
System.out.println(list);
}
private static ArrayList<String> getPredicate(String[] strings,Predicate<String> p1,Predicate<String> p2){
ArrayList<String> list = new ArrayList<>();
for (String s: strings
) {
if(p1.and(p2).test(s)){
list.add(s);
}
}
return list;
}
}
表示接受一个参数并产生结果的函数。
//int->string
public class Jademo {
public static void main(String[] args) {
String s1 = iToS(5, s -> {
return s.toString();
});
System.out.println(s1);
}
private static String iToS(Integer i, Function<Integer,String> f){
return f.apply(i);
}
}
//string->int
public class Jademo {
public static void main(String[] args) {
int i = sToI("135", s -> {
return Integer.parseInt(s);
});
System.out.println(i );
}
private static int sToI(String s,Function<String,Integer> f){
return f.apply(s);
}
}
public class Jademo {
public static void main(String[] args) {
sToI("136",s->Integer.parseInt(s),s->s+1);
}
private static void sToI(String s,Function<String,Integer> f1,Function<Integer,Integer> f2){
Integer tep = f1.apply(s);
Integer tep1 = f2.apply(tep);
System.out.println(tep1);
}
}
//string->int->int+1
表示接受单个输入参数并且不返回结果的操作。 与大多数其他功能接口不同, Consumer
预期通过副作用进行操作
方法:accept 和andThen
和functional和predicate不同的时,他不用返回任何值。
要实现接口,那么接口中的全部方法都要实现。
但是接口方法前加上default,可以不实现。
但也能重写。
public interface Flyable {
void fly(String s);
void run(String s);
default void flyAndrun(){
System.out.println("fly和run");
}
}
public class FlyableImp implements Flyable {
@Override
public void fly(String s) {
System.out.println("fly");
}
@Override
public void run(String s) {
System.out.println("run");
}
//下面可以不实现,
@Override
public void flyAndrun() {
System.out.println("重写了");
}
}
首先不能被重写。
其次只能通过接口名调用, 不能通过实现类名或者对象名调用。
防止 (一个实现类implements多个接口,那么有重复名称的静态类。)
public interface demo{
public static void show(){
System.out.println("11");
}
}
//只能这样用
demo.show();
java 9(即jdk 1.9) 新增加的内容。
public interface Flyable {
default void show1(){
show();
}
private void show(){
System.out.println("11");
}
}
函数式编程风格。
生成流
通过数据源(集合数组等)生成流
如list.stream()
中间操作
做出某种程度的数据过滤/映射,然后返回一个新的流,交给下一个操作使用
如 filter
中结操作
一个流只能有一个终结操作,当这个操作执行完后,流就被用光了,无法再被操作。
如forEach()
public class Jademo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("张无忌");
list.add("张无忌他哥");
list.add("张无忌特美");
list.add("张三丰");
list.add("张敏");
list.add("李小龙");
list.add("球球呀");
System.out.println(list);
ArrayList<String> list1 = new ArrayList<>();
list.stream().filter(s->{
return s.startsWith("张");
}).filter(s->{
return s.length()>=3;
}).forEach(s-> System.out.println(s));
}
}
filter(Predicate predicate)
limit(long maxSize)
截取前面maxSize个数据,返回流
skip(long n)
跳过指定参数个数的数据,返回由该流的剩余元素组成的流
concat(Stream a,stream b) ,静态方法。
合并a和b两个流为一个流。stream.concat();
distinct()
返回由该流的不同元素组成的流
public class Jademo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("张无忌");
list.add("张无忌他哥");
list.add("张无忌特美");
list.add("张三丰");
list.add("张敏");
list.add("李小龙");
list.add("张三丰");
ArrayList<String> list1 = new ArrayList<>();
//1.filter()使用
Stream<String> stringStream = list.stream().filter(s -> {
return s.length() == 3;
});
Stream<String> stringStream1 = list.stream().filter(s -> {
return s.startsWith("张");
});
System.out.println("----------------------");
//2.limit()
list.stream().limit(3).forEach(System.out::println);
System.out.println("----------------------");//输出前三个
//3.skip()
list.stream().skip(4).forEach(System.out::println);
System.out.println("----------------------");//跳过前4个,输出后面
//4. concat()
Stream.concat(stringStream,stringStream1).forEach(System.out::println);
System.out.println("----------------------");
//5. distinct()
Stream.concat(stringStream,stringStream1).distinct().forEach(System.out::println);
//错误,stream has already been operated upon or closed
//第四步操作已经将流关闭了。
}
}
sorted()和sorted(Comparator comp)排序
public class Jademo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("123");
list.add("4");
list.add("6");
list.add("456");
list.add("7");
list.add("1");
//默认是自然排序
list.stream().sorted().forEach(s-> System.out.println(s));
//带comparator的自定义排序
list.stream().sorted((s1,s2)->{
return s1.length()-s2.length();
}).forEach(s-> System.out.println(s));
}
}
collect() 接口
某个stream.collect(Collectors.toList())
使用类的class属性
调用对象的getClass()
使用Class类中的forName(String className) 最为灵活
public class Jademo {
public static void main(String[] args) throws ClassNotFoundException {
Deom deom = new Deom();
Class<? extends Deom> aClass = deom.getClass();//使用对象的getClas
Class<Deom> deomClass = Deom.class;//使用类的class属性
Class<?> deom1 = Class.forName("Deom");//使用Class类,最为灵活
System.out.println(deom1);
System.out.println(aClass==deomClass&&aClass==deom1);//true
}
}
getConstructors
获取所有public构造方法,返回数组
getDeclaredConstructors
所有构造方法
getConstructor(Class>…parameterTypes)
返回单个公共构造方法对象。
无参代表返回的是无参构造
getDeclaredConstructor(Class>…parameterTypes)
返回单个构造方法对象
import java.lang.reflect.Constructor;
public class Jademo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
Class<?> deom = Class.forName("Deom");//字节码文件
Constructor<?>[] deoms = deom.getConstructors();
for (Constructor c:deoms){
System.out.println(c);
}
System.out.println("-----------");
Constructor<?>[] declaredConstructors = deom.getDeclaredConstructors();
for (Constructor constructor:declaredConstructors) {
System.out.println(constructor);
}
System.out.println("------------");
Constructor<?> constructor = deom.getConstructor(String.class,String.class);
//不存在这个构造方法,异常。由于是抛出异常,所以程序会终止。可catch一下
System.out.println(constructor);
System.out.println("------------");
Constructor<?> declaredConstructor = deom.getDeclaredConstructor(String.class);
System.out.println(declaredConstructor);
}
}
//完全输出
public Deom()
public Deom(java.lang.String,java.lang.String,int)
-----------
private Deom(java.lang.String)
public Deom()
public Deom(java.lang.String,java.lang.String,int)
------------
java.lang.NoSuchMethodException: Deom.<init>(java.lang.String, java.lang.String)
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getConstructor(Class.java:1825)
at Jademo.main(Jademo.java:19)
null
------------
private Deom(java.lang.String)
Deom demo=new Deom("qiuqiu","China",50);
sout(demo)
public class Jademo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> aClass = Class.forName("Deom");// 获得到了字节码文件
Constructor<?> constructor = aClass.getDeclaredConstructor(String.class, String.class, int.class);//注意,参数个数要一致。
Object asd_ = constructor.newInstance("qiuqiu","China",50);
System.out.println(asd_);
}
}
//访问一个私有
public class Jademo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> aClass = Class.forName("Deom");
Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class);
System.out.println(declaredConstructor.newInstance("qiuqiu").toString());
}
}
异常
Class Jademo can not access a member of class Deom with modifiers "private"
public class Jademo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> aClass = Class.forName("Deom");
Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);//取消访问检查
System.out.println(declaredConstructor.newInstance("qiuqiu").toString());
}
同理,私有的要setAccessible(true)
getField() ,getFields()
得到public 变量
getDeclaredField() ,getDeclaredFileds()
得到所有对象
public class Jademo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class<?> deom = Class.forName("Deom");
Constructor<?> declaredConstructor = deom.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
Object o = declaredConstructor.newInstance("qiuqiu");
Field age = deom.getDeclaredField("age");
age.setAccessible(true);//私有成员变量
age.set(o,50);
System.out.println(o);//将o的age 字段设置为50
}
}
public class Jademo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class<?> deom = Class.forName("Deom");
Constructor<?> declaredConstructor = deom.getDeclaredConstructor();
Object o = deom.newInstance();
Field name = deom.getDeclaredField("name");
name.setAccessible(true);
name.set(o,"qiuqiu");
Field address = deom.getDeclaredField("address");
address.setAccessible(true);
address.set(o,"china");
Field age = deom.getDeclaredField("age");
age.setAccessible(true);
age.set(o,50);
System.out.println(o);
}
}
getMethods()
连继承的public方法也都返回了
getDeclaredMethods()
返回非继承所有方法
getDeclaredMethod(方法名称,参数.class)
public class Jademo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class> deom = Class.forName("Deom");
Constructor> declaredConstructor = deom.getDeclaredConstructor();//无参构造方法
Object o = deom.newInstance();//由无参构造方法 创建对象
Field age = deom.getDeclaredField("age");
age.setAccessible(true);
age.set(o,50);
Method getAdd = deom.getDeclaredMethod("getAdd", int.class);//此成员方法有一个int值的参数
getAdd.setAccessible(true);
getAdd.invoke(o,30);//调用o对象的getAdd()方法,参数是30
//带返回值的成员方法
Method getAdd = deom.getDeclaredMethod("getAdd", int.class);
Object invoke = getAdd.invoke(o, 30);
System.out.println(invoke);
}
}
ArrayList<Integer> list = new ArrayList<>();
list.add(126);
Class<? extends ArrayList> aClass = list.getClass();
Method add = aClass.getDeclaredMethod("add", Object.class);
add.invoke(list,"pop");
add.invoke(list,"998+");
for (Object a:list){
System.out.println(a);
}