A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 钟道上 中级黑马   /  2015-1-15 19:20  /  1560 人查看  /  12 人回复  /   2 人收藏 转载请遵从CC协议 禁止商业使用本文

打印    ******
            *****
             ****
              ***
               **
                *

  1. StringBuffer sb=new StringBuffer();
  2. for(int i=0;i<6;i++){
  3. for(int j=0;j<i;j++){
  4. sb.append(" ");
  5. }
  6. for(int k=i;k<6;k++){
  7. sb.append("*");
  8. }
  9. sb.append("\r\n");
  10. }
  11. BufferedWriter bw=new BufferedWriter((new FileWriter("D:\\pt.txt")));
  12. String line=sb.toString();

  13. bw.write(line);
  14. bw.close();
复制代码


暴力反射
  1. package com.itheina;

  2. import java.lang.reflect.*;

  3. public class fansheDemo {
  4. public static void main(String[] args) throws Exception{
  5. // 张老师在视频教授的方法,是直接创建一个带参数的学生所以能调用
  6. Student d=new Student(4,"水英");

  7. Field f=d.getClass().getDeclaredField("age");

  8. // 由于newInstance方法空参数,而我的Student类没有空参数的构造函数,所以错误,在Student钟加入空参数即可

  9. Class cls=Class.forName("com.itheina.Student");
  10. Object obj=cls.newInstance();

  11. f.setAccessible(true);

  12. System.out.println(f.get(obj));//空参数的构造函数是8
  13. System.out.println(f.get(d));//具有参数的构造函数是4

  14. }
  15. }



  16. class Student{
  17. private int age=8;
  18. public String name="ss";
  19. // 增加了一个空的构造函数
  20. Student(){

  21. }

  22. Student(int age,String name){
  23. this.age=age;
  24. this.name=name;
  25. }

  26. }
复制代码




12 个回复

倒序浏览
谢谢楼主分享!
回复 使用道具 举报
尽管还看不懂,不过还是谢谢啊,先收藏着吧。
回复 使用道具 举报
果真有反射的题目,谢谢分享!
回复 使用道具 举报
有点看不懂,但是谢谢楼主哦
回复 使用道具 举报
进来看看,谢谢分享
回复 使用道具 举报
郑豪 中级黑马 2015-1-15 23:30:06
7#
谢谢分享。。。。。
回复 使用道具 举报
感谢分享,收藏了!
回复 使用道具 举报
谢谢楼主!
回复 使用道具 举报
Class里面有方法是可以获取带参的构造函数, getConstructor这个方法,如果不能更改代码,你怎么加空参数的构造函数, 最后用Constructor 里面也有newInstance 方法创建带参的实力对象就行了
回复 使用道具 举报
你的题好简单啊!
回复 使用道具 举报
多谢楼主
回复 使用道具 举报
谢谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马