Java 如何在方法运行时获得当前方法的Method(实例)?

Python017

Java 如何在方法运行时获得当前方法的Method(实例)?,第1张

Foible 朋友的说法不对。

B b=new B()这种方式,实际上是实例化了子类的对象,注意:内存中还是子类对象。

((A)b).m() 表面上看起来是父类对象了,但是由于内存中是子类对象,所以调用的还是子类方法

A b=new B()

b.m()

这种方法和你写的实际是一个效果,虽然上溯造型到了父类,由于子类重写了父类的方法,调用的还是子类的方法(也就是所:方法的实现,最后是在子类中实现的)。

所以,总结如下:

如果子类没有重写父类的方法,调用父类的方法的时候,实际上是去父类的内存中实现,可以调用父类方法。

如果子类重写了父类的方法,那么,你虽然上溯造型到了父类,由于内存还是子类,该方法的实现还是在子类,所以用实例化的对象是调用不到父类的,这种情况下,只能用super关键字。

用static的情况不讨论的情况下不讨论是这样的,不知道到您是否不满意,不满意的话可以发消息继续讨论。

1、利用System.getProperty()函数获取当前路径:

System.out.println(System.getProperty("user.dir"))//user.dir指定了当前的路径

2、使用File提供的函数获取当前路径:

File directory = new File("")//设定为当前文件夹

try{

System.out.println(directory.getCanonicalPath())//获取标准的路径

System.out.println(directory.getAbsolutePath())//获取绝对路径

}catch(Exceptin e){}

File.getCanonicalPath()和File.getAbsolutePath()大约只是对于new File(".")和new File("..")两种路径有所区别。

# 对于getCanonicalPath()函数,“."就表示当前的文件夹,而”..“则表示当前文件夹的上一级文件夹

# 对于getAbsolutePath()函数,则不管”.”、“..”,返回当前的路径加上你在new File()时设定的路径

# 至于getPath()函数,得到的只是你在new File()时设定的路径

比如当前的路径为 C:\test :

File directory = new File("abc")

directory.getCanonicalPath()//得到的是C:\test\abc

directory.getAbsolutePath() //得到的是C:\test\abc

direcotry.getPath() //得到的是abc

File directory = new File(".")

directory.getCanonicalPath()//得到的是C:\test

directory.getAbsolutePath() //得到的是C:\test\.

direcotry.getPath() //得到的是.

File directory = new File("..")

directory.getCanonicalPath()//得到的是C:\

directory.getAbsolutePath() //得到的是C:\test\..

direcotry.getPath() //得到的是..

Date date=new Date()

DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

String time=format.format(date)

不同的方法介绍如下:

1、通过Date类来获取当前时间。

Date day=new Date()

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

System.out.println(df.format(day))

2、通过System类中的currentTimeMillis方法来获取当前时间。

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")  System.out.println(df.format(System.currentTimeMillis()))

3、通过Calendar类来获取当前时间。

Calendar c = Calendar.getInstance()//可以对每个时间域单独修改

int year = c.get(Calendar.YEAR)

int month = c.get(Calendar.MONTH)

int date = c.get(Calendar.DATE)

int hour = c.get(Calendar.HOUR_OF_DAY)

int minute = c.get(Calendar.MINUTE)

int second = c.get(Calendar.SECOND)

System.out.println(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second)

4、通过Date类来获取当前时间。

Date date = new Date()

String year = String.format("%tY", date)

String month = String.format("%tB", date)

String day = String.format("%te", date)

System.out.println("今天是:"+year+"-"+month+"-"+day)